【问题标题】:React-Native How to update parent state variable from child componentReact-Native 如何从子组件更新父状态变量
【发布时间】:2019-07-30 10:15:14
【问题描述】:

我在 react-native 中使用 Modal 展示一个组件。所以在子组件(在父组件顶部显示为模态的组件)中,我试图更新父组件的状态变量,但它会引发错误,例如“'changeModalVisibility' is missing in props validation”。

请帮我解决这个问题。

相关代码如下:

// Parent Class in render
<SafeAreaView style={styles.container}>
        <Modal
          animationType="slide"
          transparent={false}
          visible={this.state.isModalVisible}
          onRequestClose={() => { this.changeModalVisibility(false) }}
        >
          <ChildClass
            changeModalVisibility={this.changeModalVisibility}
          />
        </Modal>
</SafeAreaView>
// Outside Render function
changeModalVisibility = (bool) => {
 this.setState({ isModalVisible: visible });
}

// In Child Class 
<TouchableHighlight
              underlayColor="none"
              onPress={this.props.closeButtonTapped}
              style={{ alignItems: 'center', justifyContent: 'center', }}
            >
              <Text style={{
                color: 'white',
                marginTop: 10,
                marginLeft: 20,
                fontWeight: '600',
                fontSize: 18,
              }}
              >Close
              </Text>
            </TouchableHighlight>

closeButtonTapped() {
this.props.changeModalVisibility //"**'changeModalVisibility' is missing in props validation**"
}

【问题讨论】:

  • 这是issue with your prop-types,不是功能错误。
  • 在closeButtonTapped()方法的末尾添加大括号()方法如this.props.changeModalVisibility()
  • @KaushikRadadiya:它的抛出错误“期望一个赋值或函数调用,而是看到一个表达式。道具验证中缺少 &”
  • 您是否尝试过通过函数调用传递参数?像这样 this.props.changeModalVisibility(false)
  • @KaushikRadadiya:我试过了,效果很好,谢谢兄弟。

标签: react-native react-native-android react-native-ios react-native-navigation


【解决方案1】:

父组件中的子组件有 changeModalVisibility 属性。
您应该致电
this.props.changeModalVisibility(true) or this.props.changeModalVisibility(false)
内部子组件。当你想从 prop 执行函数时,请确保使用箭头函数:

changeModalVisibility={this.changeModalVisibility}

changeModalVisibility = (visible) => {
 this.setState({ isModalVisible: visible });
}

在子组件中的 onPress 道具应该是这样的:

onPress={() => this.closeButtonTapped()}

【讨论】:

  • 我已经尝试过了,它抛出了同样的错误,并且父级中的方法没有被调用
  • 答案已更新 :) 您在 onPress 中创建了函数并调用了 prop。
  • “changeModalVisibility={this.changeModalVisibility.bind(this)}”这个应该写在Parent组件的构造方法中吗?我通过保留 Parent 方法的构造函数来保持这一点,并尝试在子组件中记录 props,返回空数据并且没有调用父方法
  • 在父组件中是的。
猜你喜欢
  • 2021-12-27
  • 2020-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-14
  • 2020-05-31
  • 2018-10-09
相关资源
最近更新 更多