将值动态传递到子组件会本机响应



App.js

render() {
return (
<View style={{ flex: 1, marginTop: 20 }}>
<Button
title="Learn More"
color="#841584"
accessibilityLabel="Learn more about this purple button"
onPress={() => {
(this.state.dadda = '2017-09-07');
}}
/>
<EventCalendar
eventTapped={this._eventTapped.bind(this)}
events={this.state.events}
width={width}
initDate={this.state.dadda}
scrollToFirst={false}
/>
</View>
); }

这是我的父组件,我想将initDate传递给事件日历组件,我想更新按下按钮的日期?

您不应该通过直接将值分配给state变量改变state,而应使用setState来实现这一点。

<Button
title="Learn More"
color="#841584"
accessibilityLabel="Learn more about this purple button"
onPress={() => this.setState({dadda: '2017-09-07'})}
/>

您将dadaa设置为状态的方式不正确,请改用this.setState函数,请查看文档。

将 onPress 处理程序更改为

...
< Button
title = "Learn More"
color = "#841584"
accessibilityLabel = "Learn more about this purple button"
onPress = {
() => {
this.setState({
dadda:'2017-09-07'
});
}
}
/>
...

另外,不要在 render 中声明函数,而是将其保留在类级别,例如

onPressHandler = () => {
this.setState({
dadaa: 'aaaa'
});
}
render() {
return (
...
<
Button
...
onPress = {this.onPressHandler}
...
/>
...
);
}

希望这会有所帮助!

最新更新