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

前端 未结 4 1496
面向向阳花
面向向阳花 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:48

    You don't need a complicated react solution to this problem, just a little common sense about when to update state. The best way to achieve this is to encapsulate your setState call within a timeout.

    class Element extends React.Component {
        onChange = (e) => {
            clearTimeout(this.setStateTimeout)
            this.setStateTimeout = setTimeout(()=> {
                this.setState({inputValue: e.target.value})
            }, 500)
        }
    }
    

    This will only set state on your react element a 500ms after the last keystroke and will prevent hammering the element with rerenders as your user is typing.

提交回复
热议问题