如何从无关组件传递道具

时间:2019-05-09 16:45:10

标签: reactjs parameter-passing

我需要使用表头组件中的数据(2个下拉列表和一个“应用”按钮)来绘制表,而表头,表部分和页脚彼此无关 我尝试在单独的Utils文件中创建一个数组,当单击“应用”按钮时填充该数组,该数组作为

<Table data={utils.sortArray}/>

当在标题组件中单击“应用”按钮时,数据正在填充sortArray时,其显示的长度为0 点击“应用”按钮后,新的数组数据应传递给表组件

1 个答案:

答案 0 :(得分:0)

If you need the table to update based on input in the header the components aren't really unrelated (they are related through the data they have in common / are sharing).

To communicate between the two you will need a way to pass the data - the logical approach is to have the parent component coordinate between the two as it is contextually aware of both. In this case, you can:

  1. Pass callback a prop to your header component that you call with the required data
  2. Store the data sent in the callback in the parent's state
  3. Pass the state data to your Table.

E.g., in your parent component:

state = {
  sortArray: '', // What ever your default value is
}

onSort = (sortArray) => {
  this.setState({
    sortArray,
  });
}

render() {
  ...
  <Header onSort={this.onSort} />
  ...
  <Table sortArray={this.state.sortArray} />
  ...
}

And then call onSort in your header with the required value as needed.