【问题标题】:How to change value of parent component's state via the child component?如何通过子组件改变父组件的状态值?
【发布时间】:2020-01-13 06:24:41
【问题描述】:

这就是我正在做的事情:

https://codepen.io/nisofwareengineer/pen/dybeObW?editors=0110

我想要发生的事情:

家长 = 董事会, 孩子 = 正方形

点击九个框中的任意一个后,父组件状态的player var应该从1变为2。这意味着当player var为1且O为1时,点击其中一个框时会显示一个X当 player var 为 2 时单击其中一个框时显示。

这需要通过孩子来完成

关注这个https://ourcodeworld.com/articles/read/409/how-to-update-parent-state-from-child-component-in-react之后

我做了以下事情:

在母板中:

this.changePlayer = this.changePlayer.bind(this)

changePlayer(){
    this.setState({
     player: this.state.player == 1 ? 2 : 1  
    })
  }

renderSquare(i) {
    return <Square value={i} player={this.state.player} changePlayer = {this.changePlayer} />;
  }

在子 Square 中:

render() {
    return (
      <button
        className="square"
        onClick={() => {
          this.setState({
            value:
              this.state.value == "" && this.props.player == 1
                ? "X"
                : (this.state.value == "" && this.props.player == 2 ? "O" : ""),
          });
          this.props.changePlayer

        } }
      >

我希望传递下来的方法 changePlayer 允许在单击任何子组件的按钮时更改父状态 var player

不幸的是,这似乎不起作用。

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    问题是你只需要在你的事件中调用 this.props.changePlayer 因为 this.props.changePlayer 是一个函数。因为您还需要在 onClick 事件中执行其他操作,所以您可以使用 onMouseUp 作为更改播放器的替代方法。你可以这样解决:

    <button
        className="square"
        onClick={() => {
          this.setState({
            value:
              this.state.value == "" && this.props.player == 1
                ? "X"
                : (this.state.value == "" && this.props.player == 2 ? "O" : ""),
            player: this.props.player == 1 ? 2 : 1
          });                 
        } }
        onMouseUp={this.props.changePlayer}
      >
        {this.state.value}
      </button>
    

    最正确的方法是使用 redux,因为在 react 中它不应该将数据从子级传递给父级。

    【讨论】:

      【解决方案2】:

      在父母中:

      changePlayer(value) {
          this.setState({
            player: value === 1 ? 2 : 1
          })
        }
      

      在孩子中:

            render() {
          return <button
            className="square"
            onClick={() => {
          let val = this.state.value === "" && this.props.player === 1 ? "X" : (this.state.value === "" && this.props.player === 2 ? "O" : "")
          this.props.changePlayer(val)
            }}>button</button>
        }
      

      【讨论】:

      • 嗯。据我所知,子组件会将 val 传递给 changePlayer,然后更改父组件的状态。但是,val 本身只会评估为“X”或“O”。当其中任何一个被传递到 changePlayer 时,value 将始终评估为 1,因为我们将得到 'X' ===1 或 'O' === 1 这将始终为 false,因此 value 将被分配 1,因此 player将被分配 1. 我在这里遗漏了什么吗?
      猜你喜欢
      • 2017-07-10
      • 2016-12-23
      • 2020-07-21
      • 1970-01-01
      • 2020-09-18
      • 2021-06-08
      • 2016-12-21
      • 1970-01-01
      相关资源
      最近更新 更多