我的 React 应用有三个组件,其中两个是子组件,另一个是父组件。我需要通过父组件将一个数据(projectId)从一个子组件传递到另一个子组件,并在接收到数据后触发一个函数。例如,我正在从 ChildOne 发送 projectId 到 Parent,然后从 Parent 发送 projectId 到 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>
)
}
}
ChildTwo:
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>
)
}
}
this.props.sendOneId
?解决方案将取决于你的用例。 - DeepakcomponentWillReceiveProps
应该可以正常工作。 - Vishal