[当父组件设置状态(itemSelected:项)时,我也希望子组件设置状态(isShowForm:true),那么是否有任何信号或条件允许我执行该操作?
<pre>
//this is child Component
class HeaderComponent extends Component {
constructor(props) {
super(props);
this.state = {
isShowForm: false,
};
}
handleEdit = () =>{
if(any signal?){
this.setState({isShowForm:true})
}
}
export default HeaderComponent;
//this is parent Component
class Task extends Component {
constructor(props){
super(props);
this.state = {
itemSelected: null,
}
}
handleEdit = (item) => {
this.setState({itemSelected: item})
}
render() {
let {itemSelected} = this.state;
return(
HeaderComponent itemSelected={itemSelected}/>
)
</pre>
您可以将所需的状态从父组件传递给子组件,并在子组件中使用componentDidUpdate
生命周期来收听道具并做出相应的反应。
class HeaderComponent extends Component {
constructor(props) {
super(props);
this.state = {
isShowForm: false,
};
}
componentDidUpdate(prevProps) =>{
// Any identifying property to see if the itemSelected object has indeed changed. I'm just assuming that it has a unique ID
if(prevProps.itemSelected && prevProps.itemSelected.id !== this.props.itemSelected.id) {
this.setState({ isShowForm: true })
}
}
export default HeaderComponent;
//this is parent Component
class Task extends Component {
constructor(props){
super(props);
this.state = {
itemSelected: null,
}
}
handleEdit = (item) => {
this.setState({itemSelected: item})
}
render() {
let {itemSelected} = this.state;
return(
<HeaderComponent itemSelected={itemSelected}/>
)