【问题标题】:How to get state data from child to parent component?如何从子组件获取状态数据到父组件?
【发布时间】:2019-05-17 19:43:43
【问题描述】:

我有两个组件,TabTble 和 MultiSelect。 我在 TabTble 中渲染 MultiSelect 组件,所以父组件是 TabTble,子组件是 MultiSelect。 我的子 (MultiSelect) 组件中有一些状态,如何在 TabTble 组件中获取它。

const selectedData = this.state.multi;这是状态数据

const {selectedData } = this.props 这样我把它作为道具传递了

<MultiSelect selectedData ={ selectedData } /> 并像这样在子组件中渲染。

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    组件间共享状态变量的正确方式是通过redux store。主要优点是,如果您有超过 2 个组件,那么您可以在所有组件中使用存储状态并通过调度操作来修改它,这再次将使修改后的状态可用于所有组件。

    【讨论】:

      【解决方案2】:

      假设你有这两个组件,你可以这样做:

      class TabTble extends Component  {
      handleChildData = (fromMultiSelectData) => {
      //Do whatever you want to do from this child data
      }
      return (
      <MultiSelect selectedData ={ selectedData } handleChildData = {this.handleChildData}/>
      );
      }
      

      而在 MultiSelect 组件中:

      class MultiSelect extends Components {
         state = {
          localData:[] //local state data which we want to send to parent components
      }
      handleClick = () => {
      let {localData} = this.state;
      this.props.handleChildData(localStateData)
      }
      render(){
      let {selectedData} = this.props;
      return(
      somechild
      //Note you need some event handler like onChange,onClick to pass this data up
      <div onClick={this.handleClick}>Send Data to parent</div> //you can pass any other data from here
      )
      }
      }
      

      // 请注意,在设计 React 代码时,这种设计模式并不好。当你有这样的 prop 向下钻取或使用上下文 api 或 redux 的良好状态管理时,它总是推荐。

      【讨论】:

        【解决方案3】:

        我认为您应该更改一些代码。将要更改的状态放入 Parent 并将其作为 props 传递给 child,在 child 中您可以更改状态。

        如果你不使用 Redux,我认为这是正确的方法。

        看那个例子:

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-03-31
          • 2018-03-18
          • 2019-06-03
          • 1970-01-01
          相关资源
          最近更新 更多