将值动态传递给子组件进行本机反应

时间:2018-09-09 13:28:12

标签: react-native

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传递给事件日历组件,我想在按下按钮时更新日期?

2 个答案:

答案 0 :(得分:0)

您不应通过直接将值分配给state变量变异 state ,而应使用setState来实现

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

答案 1 :(得分:0)

dadaa设置为状态的方式不正确,请改用this.setState函数,看看doc

将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}
      ...
    />
    ...
  );
}

希望这会有所帮助!