避免从“输入"不断重新渲染;或“文本区域"在反应 js [英] avoid constant re-render from "input" or "textarea" in react js
问题描述
目前在react js中,当我想绑定一个文本区域或一个带有状态"的输入时,每次用户输入一个字母时,我都需要设置onChange方法和setState()
我听说如果你 setState 反应 js 刷新并重新渲染这个组件中的所有内容
有没有更有效的方法来做到这一点?在这种情况下使用shouldComponentUpdate"将是不正确的,因为如果我不进行状态"更新,所有用户输入都会被卡住..
嗯,这就是你在 React 中实现受控输入元素的方式.
但是,如果性能是您的主要关注点,您可以将输入元素隔离在一个单独的有状态组件中,从而仅触发自身的重新渲染,而不是整个应用程序的重新渲染.
比如:
class App 扩展组件 {使成为() {返回 (<div>...<我的输入/>...
);}}类 MyInput 扩展组件 {构造函数(){极好的();this.state = {值:"};}更新 = (e) =>{this.setState({value: e.target.value});}使成为() {返回 (<input onChange={this.update} value={this.state.value}/>);}}
<小时>
或者,您可以只使用不受控制的输入元素.例如:
class App 扩展组件 {使成为() {返回 (<div>...<input defaultValue=""/>...
);}}
不过,请注意通常建议使用受控输入.
Currently in react js, when I want to bind a text area or an input with a "state", I will need to set the onChange method and setState() everytime user type in a single letter
I heard if you setState react js refresh and re-render everything in this component
Is there any more efficient way to do so? using "shouldComponentUpdate" will be improper in this case since if I don't make "state" update, all user input will be stuck..
Well, that's how you implement controlled input elements in React.
However, if performance is a major concern of yours, you could either isolate your input element in a separate stateful component, hence only triggering a re-render on itself and not on your entire app.
So something like:
class App extends Component {
render() {
return (
<div>
...
<MyInput />
...
</div>
);
}
}
class MyInput extends Component {
constructor() {
super();
this.state = {value: ""};
}
update = (e) => {
this.setState({value: e.target.value});
}
render() {
return (
<input onChange={this.update} value={this.state.value} />
);
}
}
Alternatively, you could just use an uncontrolled input element. For example:
class App extends Component {
render() {
return (
<div>
...
<input defaultValue="" />
...
</div>
);
}
}
Though, note that controlled inputs are generally recommended.
这篇关于避免从“输入"不断重新渲染;或“文本区域"在反应 js的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!