背景:
在<TextArea>
的onChange
方法中使用setState
來保存value的話,會致使輸入卡頓,緣由是用戶在輸入時,一直在setState
,致使整個頁面一直從新渲染react
主頁面:antd
import React, { Component, } from 'react'; import { Input } from 'antd'; const { TextArea } = Input; class CustomCompent extends Component { constructor(props) { super(props); this.state = { targetValue: '', }; } handleChange = e => { let targetValue = e.target.value; this.setState({ targetValue, }); }; render() { const { targetValue } = this.state; return ( <> xxxx xxxx <TextArea onChange={this.handleChange} value={targetValue} /> <p>{targetValue.length}/100</p> </> );}
解決方法:
將<TextArea>
組件單獨封裝成一個組件(component),這樣就只會觸發自身從新渲染而不是整個頁面!this
TextArea 組件:spa
import React from 'react'; import { Input } from 'antd'; const { TextArea } = Input; class CountTextArea extends React.PureComponent { constructor(props) { super(props); this.state = { targetValue: '', }; } handleChange = value => { let targetValue = value.target.value; this.setState({ targetValue, }); }; render() { const { setRef } = this.props; const { targetValue } = this.state; return ( <> <TextArea onChange={this.handleChange} value={targetValue} ref={setRef} /> <p>{targetValue.length}/100</p> </> ); } } export default CountTextArea;
主頁面:code
import React, { Component, } from 'react'; import { Button } from 'antd'; import CountTextArea from './CountTextArea'; class CustomCompent extends Component { componentDidMount() { this.customTextArea = React.createRef(); } handleOk = () => { if (this.customTextArea && this.customTextArea.current) { //發送內容 let value =this.customTextArea.current.textAreaRef.value //xxx } } render() { return ( <> <CountTextArea handleOk={this.handleOk} setRef={this.customTextArea} /> <Button onClick={this.handleOk}>發送</Button> </> ); } }
這樣就可讓用戶愉快地輸入的同時,setState textarea
的值啦~component
(完)rem