React - 如何调用 Child 中的方法以设置状态,仅在调用 Parent 中的方法时?



我有一个父组件和 2 个子组件。每个子字段都是一个输入字段,第二个输入取决于从第一个输入字段中选择的内容。是否可以在 react 中调用函数洞察兄弟姐妹 2,只有当父级中的函数被执行时?就我而言:孩子 1 提供 ID,父级使用 ID,孩子 2 应该使用相同的 ID 发出 http 请求。

在我的代码下面(我省略了很多,所以我没有太多(不必要的代码),所以如果我错过了什么,请告诉我)在 Parent 内部,"updateId"方法从 child1 接收其参数,只有当这种情况发生时(提供了 id),只有这样我才想在兄弟姐妹中调用"getData"方法。我在想我可以在设置为 true 的 Parent 中创建布尔值,当给出 id 时,将其传递给兄弟姐妹,仅在其为 true 时才调用"getData"方法,但据我了解,这不可能做出反应?!我该怎么做?

PS - 我故意在我的子组件中设置状态,因为我试图保持输入(孩子=输入)独立,这很容易交换。

export default class Parent extends React.Component {
constructor(props) {
super(props)
this.state = {
id: ""
}
this.updateId=this.updateId.bind(this);
}
updateId (id){
this.setState({
id:id
})
}
render() {
return (
<div>
<Child onChange={this.updateId} />
<Sibling id={this.state.id}/>
</div>
)
}
};
import apicall from :/....jsx;
export default class Sibling extends React.Component {
constructor(props) {
super(props)
this.state = {
siblings: []
}
this.getData=this.getData.bind(this);
}
getData (this.props.id){
apiCall(this.props.id).then(response=> {
this.setState({
siblings:response
})
}
render() {
return ...
}
};
export default class Child extends React.Component {
...
get ID
...
call this.props.onChange(selected.value)
};

在这种情况下,我通常会在父级(或像 Redux 这样的系统中)保持我的状态,并保持我的子组件简单而愚蠢。因此,我会在父级中执行 API 工作,并将结果数据传递给子级。

也就是说,如果 ID 属性发生更改,您的Sibling组件可以挂接到componentWillReceiveProps并更新其状态。

https://reactjs.org/docs/react-component.html#componentwillreceiveprops

为了避免子对子通信之间的混淆,请使用Redux,它可以帮助您实现所需的功能。它还可以帮助您制作哑组件。

最新更新