首页 文章

避免在react js中从“input”或“textarea”继续重新渲染

提问于
浏览
3

当前在反应js中,当我想要将文本区域或输入与“状态”绑定时,我将需要在每个用户类型的单个字母中设置onChange方法和setState()

我听说如果你setState反应js刷新并重新渲染这个组件中的所有内容

有没有更有效的方法呢?在这种情况下使用“shouldComponentUpdate”将是不正确的,因为如果我不进行“状态”更新,则所有用户输入都将被卡住..

2 回答

  • 4

    正如@Chris所说,你应该创建另一个组件来优化重新渲染到只有指定的组件 .

    但是,有些用例需要更新父组件或使用输入中输入的值向一个reducer发送操作 .

    例如,我创建了一个SearchInput组件,该组件为输入中输入的每个字符更新自身,但如果至少有3个字符,则只调用 onChange 函数 only .

    注意: clearTimeout 对于在用户停止键入至少200ms时调用 onChange 函数 only 非常有用 .

    import React from 'react';
    
    class SearchInput extends React.Component {
      constructor(props) {
        super(props);
        this.tabTimeoutId = [];
        this.state = {
          value: this.props.value,
        };
    
        this.onChangeSearch = this.onChangeSearch.bind(this);
      }
    
      componentWillUpdate() {
        // If the timoutId exists, it means a timeout is being launch
        if (this.tabTimeoutId.length > 1) {
          clearTimeout(this.tabTimeoutId[this.tabTimeoutId.length - 2]);
        }
      }
    
      onChangeSearch(event) {
        const { value } = event.target;
    
        this.setState({
          value,
        });
    
        const timeoutId = setTimeout(() => {
          value.length >= this.props.minSearchLength ? this.props.onChange(value) : this.props.resetSearch();
          this.tabTimeoutId = [];
        }, this.props.searchDelay);
    
        this.tabTimeoutId.push(timeoutId);
      }
    
      render() {
        const {
          onChange,
          minSearchLength,
          searchDelay,
          ...otherProps,
        } = this.props;
    
        return <input
          {...otherProps}
          value={this.state.value}
          onChange={event => this.onChangeSearch(event)}
        />
      }
    }
    
    SearchInput.propTypes = {
      minSearchLength: React.PropTypes.number,
      searchDelay: React.PropTypes.number,
    };
    SearchInput.defaultProps = {
      minSearchLength: 3,
      searchDelay: 200,
    };
    
    export default SearchInput;
    

    希望能帮助到你 .

  • 3

    好吧,这就是你在React中实现受控输入元素的方法 .

    但是,如果性能是您的主要关注点,您可以将输入元素隔离在单独的有状态组件中,因此只会触发重新呈现本身而不是整个应用程序 .

    所以类似于:

    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} />
        );
      }
    }
    

    或者,您可以使用不受控制的输入元素 . 例如:

    class App extends Component {    
      render() {
        return (
          <div>
            ...
            <input defaultValue="" />
            ...
          </div>
        );
      }
    }
    

    虽然注意到通常建议使用受控输入 .

相关问题