avoid constant re-render from “input” or “textarea” in react js

前端 未结 4 1522
面向向阳花
面向向阳花 2021-01-11 14:32

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 le

4条回答
  •  遥遥无期
    2021-01-11 14:50

    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 (
          
    ... ...
    ); } } class MyInput extends Component { constructor() { super(); this.state = {value: ""}; } update = (e) => { this.setState({value: e.target.value}); } render() { return ( ); } }

    Alternatively, you could just use an uncontrolled input element. For example:

    class App extends Component {    
      render() {
        return (
          
    ... ...
    ); } }

    Though, note that controlled inputs are generally recommended.

提交回复
热议问题