【发布时间】:2019-10-01 20:54:46
【问题描述】:
我的 React 应用程序包含三个组件。其中两个是子组件,另一个是父组件。我需要通过父组件将数据(projectId)从一个子组件传递给另一个子组件,并在接收到数据后触发一个函数。作为我的示例,我将 projectId 从 ChildOne 发送到 Parent,然后将 projectId 从 Parent 发送到 ChildTwo。 ChildTwo 有一个名为 setProject(projectId) 的函数,我需要在收到 projectID 后触发它。 问题是我无法通过单击 ChildOne 中的按钮在 ChildTwo 中触发 getProjectId 函数。我还尝试了对我不起作用的 componentDidMount 和 componentWillReceiveProps。 我该怎么做?
这是我尝试过的
ChildOne:
class ChildOne extends React.Component {
constructor(props) {
super(props);
this.state = {
projectId: 3,
};
}
sendProjectId = (projectId) => {
this.props.sendId(projectId)
}
render() {
return(
<button onClick={() => this.sendProjectId(this.state.projectId)}>
Click
</button>
)
}
}
家长:
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
projectId: '',
};
}
getId = (proId) => {
this.setState({
projectId : proId
})
}
render() {
return(
<div>
<CildOne sendId={this.getId} />
<CildTwo sendOneId={this.state.projectId} />
</div>
)
}
}
孩子二:
class ChildTwo extends React.Component {
constructor(props) {
super(props);
this.state = {
projectId: '',
};
}
getProjectId = (this.props.sendOneId) => {
//Do something with this.props.sendOneId
}
render() {
return(
<div></div>
)
}
}
【问题讨论】:
-
你打算用 ChildTwo 中的
this.props.sendOneId做什么?解决方案将取决于您的用例 -
我认为
componentWillReceiveProps在您的场景中应该可以正常工作。 -
componentWillReceiveProps已弃用。
标签: javascript reactjs