背景:
在<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