【问题标题】:Change input field when state changes after user input用户输入后状态更改时更改输入字段
【发布时间】:2016-11-25 17:19:11
【问题描述】:

当用户输入后状态发生变化时,我试图找到一种更 React 类型的方式来更改输入字段。这是我当前的设置,但我正在寻找一种方法来做到这一点,而无需在 componentWillReceiveProps 方法中向 DOM 发出信号:

export default class Example extends React.Component {

constructor(props){
  super(props);
  this.state = {title: props.arr.question};
};

componentWillReceiveProps(nextProps){
  if(nextProps.arr.question !== this.state.title){
    let id = "question" + this.props.arr.key;
    document.getElementById(id).value = nextProps.arr.question;
    this.setState({title: nextProps.arr.question});
  }
}
  render(){

  return(<div>
<input type="text" id={"question" + this.props.arr.key} defaultValue={this.state.title} placeholder="Enter your title."/>
          </div>
        )
  }
}

我的假设是,当状态发生变化时,我也会看到输入发生变化。事实上,出于某种原因,除了输入字段之外的任何元素都会发生这种情况。所以我发现的唯一想法是在 componentWillReceiveProps 方法中引用 DOM 并像这样进行更改。

有没有我不知道的更好的方法来做到这一点?

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    您可以通过将输入中的值直接设置为state 中的值来创建受控组件。查看my answer here,应用类似。

    所以在你的代码中修改为:

    export default class Example extends React.Component {
    
    constructor(props){
      super(props);
      this.state = {title: props.arr.question};
      this.handleTitleChange = this.handleTitleChange.bind(this); 
      // ^--necessary to be able to call setState
    };
    
    handleTitleChange(e){
      this.setState({title: event.target.value});
      // this updates the state as the user types into the input
      // which also causes a re-render of this component
      // with the newly update state
    }
    render(){
    
      return(
         <div>
          <input type="text" 
            id={"question" + this.props.arr.key}
            defaultValue={this.state.title} 
            placeholder="Enter your title."
            onChange={this.handleTitleChange}  // to handle the change
    
            value={this.state.title}/>  // here is where you set 
                                        // the value to current state
         </div>
      )
    }
    

    【讨论】:

    • 所以基本上只为输入创建一个单独的组件?
    • 不,您不必这样做。我已经添加了您可以对您的代码进行的修改以使其正常工作。
    • 唯一不同的是,在我输入这个特定问题时,我不是直接在这个特定输入中输入标题,而是另一个输入。但是你的解决方案奏效了。我所要做的就是删除defaultValue 属性,添加一个onChange 属性并让onChange 通过设置状态来处理标题更改,而不是直接通过vanilla JS 调用DOM。
    猜你喜欢
    • 1970-01-01
    • 2020-01-28
    • 2017-09-15
    • 1970-01-01
    • 1970-01-01
    • 2019-01-12
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    相关资源
    最近更新 更多