目录
首先,在父组件中,我想点击按钮触发事件调用方法去setState值,因为值变了所以引发子组件重新刷新加载,在子组件中检查传递给子组件的属性是否发生变化,并根据需要执行操作。
class ParentComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
cityName: 'New York',
};
}
handleChangeCity = (newCityName) => {
this.setState({ cityName: newCityName });
};
render() {
return (
<div>
<button onClick={() => this.handleChangeCity('London')}>
Change City to London
</button>
<ChildComponent cityName={this.state.cityName} />
</div>
);
}
}
class ChildComponent extends Component<any, any> {
constructor(props: any) {
super(props);
this.state = {
cityName: '',
};
}
componentWillReceiveProps(nextProps: any) {
// 检查传递给子组件的属性是否发生变化,并根据需要执行操作
alert(nextProps.cityName);
if (this.props.cityName !== nextProps.cityName) {
alert('City Name has changed');
}
}
render() {
return null; // 或其他组件的渲染内容
}
}