背景:
在<TextArea>
的onChange
方法中使用setState
来保存value的话,会导致输入卡顿,原因是用户在输入时,一直在setState
,导致整个页面一直重新渲染
主页面:
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),这样就只会触发自身重新渲染而不是整个页面!
TextArea 组件:
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;
主页面:
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
的值啦~
(完)
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。