首页 > 解决方案 > 如何通过子组件的输入字段使用 onChange 更新数组状态

问题描述

我正在尝试更新在我的父组件状态内的数组。每个子组件都是通过父组件状态数组中的一个元素创建的。现在我有一个 onChange 处理程序,它位于我的 Parent 组件中,我将它传递给我的 Child 组件。

以下是一些与此有关的片段:

家长

class PropertyBar extends Component {
  state = {
    selectedCell: graph.selectedCell,
    cellProperties: []
  }

  onChangeHandler(e) {
    let cellProperties = [...this.state.cellProperties];
    cellProperties[e.target.name] = e.target.value;
    this.setState({cellProperties});
  }

  renderPropertyList() {
    return this.state.cellProperties.map(key => {
      return <PropertyBarItem name={key.nodeName} value={key.nodeValue} onChange={this.onChangeHandler}/>
    })
  }
}

孩子

class PropertyBarItem extends Component {
  constructor(props) {
    super(props);
  }

  onChangeHandler(e) {
    if (this.props.onChangeHandler) {
      this.props.onChangeHandler(e);
    }
  }

  render() {
    return (
      <ListItem divider={true} className="property-bar-item">
        <TextField
          id="property"
          label={this.props.name}
          value={this.props.value}
          margin="dense"
          onChange={(e) => {this.onChangeHandler(e)}}
        />
      </ListItem>
    )
  }
}

我不认为我onChangeHandler在 Child 组件中正确处理了传递的内容,但我也可能有逻辑错误。

标签: javascriptreactjs

解决方案


在您的子组件中,您没有onChangeHandler正确使用该函数,因为您将它作为道具传递,onChange所以它应该像下面的代码

class PropertyBarItem extends Component {
    constructor(props) {
        super(props);
        this.state = {
          input: props.value
        }
    }

    onChange = (event) =>{
        this.setState({ input: event.target.value },()=>{ // callback of setState
            this.props.onChange(this.state.input) // passing the state to parent component
        })
    }

  render() {
    return (
      <ListItem divider={true} className="property-bar-item">
        <TextField
          id="property"
          label={this.props.name}
          value={this.state.input}
          margin="dense"
          onChange={this.onChange}
        />
      </ListItem>
    )
  }
}

您还需要onChangeHandle在父构造函数中绑定或使用箭头函数,如

  onChangeHandler = (e) => { // arrow function
     console.log(e.target.value) // check
     //let cellProperties = [...this.state.cellProperties];
     //cellProperties[e.target.name] = e.target.value;
     //this.setState({cellProperties});
  }

推荐阅读