如何调用 componentWillUpdate() 来更新 child 组件状态?
How to call componentWillUpdate() to update a child components state?
我的工具栏已经呈现,我现在想在需要更新它的状态时调用此工具栏上的 componentWillUpdate()?
主屏幕
constructor(){
super();
this.state = {
pagenum: 0,
toptoolbartitle: "default",
homeviewtitle: "default",
};
}
updateHomeViewTitle(viewtitle){
console.log(viewtitle);
this.state.homeviewtitle = viewtitle;
console.log("homeviewtitle is now"+this.state.homeviewtitle);
}
render() {
return (
<View style={styles.container}>
<View style={{flex:1}}>
<TopToolbarAndroid
defaulttitle={"default"} titleupdate={this.state.homeviewtitle}/>
<RNCamera updateviewtitle={this.updateHomeViewTitle.bind(this)} />
<BottomBar />
</View>
</View>
TopToolbarAndroid
constructor(props){
super();
this.props = props;
this.state = {
pagenum: 0,
title: this.props.defaulttitle
};
}
componentWillUpdate(){
console.log("component will update?");
if (this.props.titleupdate != null)
{console.log("updating toolbar title to: "+this.props.titleupdate);
this.setState({title: this.props.titleupdate});}
}
render() {
return (
<ToolbarAndroid
title= {this.state.title}
style={styles.toolbar}
/>
);
}
结果
componentWillUpdate 未更新工具栏标题,它未被调用 (re-rendered)。
您无需维护 TopToolbarAndroid
中的状态。
只需在 TopToolbarAndroid
中进行此调整即可更新标题-
title={this.props.titleupdate ? this.props.titleupdate : this.props.defaulttitle}
也去掉this.state
。
我不确定 this.props = props
在构造函数中做了什么。我只是 super(props)
。
如果这不起作用,请告诉我。请提供一个 link 给可运行的应用程序,以便人们可以有效地解决您的问题。在您的问题中添加 react-native
标签以吸引合适的人。
在此处托管您的示例 - https://rnplay.org/
我的工具栏已经呈现,我现在想在需要更新它的状态时调用此工具栏上的 componentWillUpdate()?
主屏幕
constructor(){
super();
this.state = {
pagenum: 0,
toptoolbartitle: "default",
homeviewtitle: "default",
};
}
updateHomeViewTitle(viewtitle){
console.log(viewtitle);
this.state.homeviewtitle = viewtitle;
console.log("homeviewtitle is now"+this.state.homeviewtitle);
}
render() {
return (
<View style={styles.container}>
<View style={{flex:1}}>
<TopToolbarAndroid
defaulttitle={"default"} titleupdate={this.state.homeviewtitle}/>
<RNCamera updateviewtitle={this.updateHomeViewTitle.bind(this)} />
<BottomBar />
</View>
</View>
TopToolbarAndroid
constructor(props){
super();
this.props = props;
this.state = {
pagenum: 0,
title: this.props.defaulttitle
};
}
componentWillUpdate(){
console.log("component will update?");
if (this.props.titleupdate != null)
{console.log("updating toolbar title to: "+this.props.titleupdate);
this.setState({title: this.props.titleupdate});}
}
render() {
return (
<ToolbarAndroid
title= {this.state.title}
style={styles.toolbar}
/>
);
}
结果 componentWillUpdate 未更新工具栏标题,它未被调用 (re-rendered)。
您无需维护 TopToolbarAndroid
中的状态。
只需在 TopToolbarAndroid
中进行此调整即可更新标题-
title={this.props.titleupdate ? this.props.titleupdate : this.props.defaulttitle}
也去掉this.state
。
我不确定 this.props = props
在构造函数中做了什么。我只是 super(props)
。
如果这不起作用,请告诉我。请提供一个 link 给可运行的应用程序,以便人们可以有效地解决您的问题。在您的问题中添加 react-native
标签以吸引合适的人。
在此处托管您的示例 - https://rnplay.org/