React-Native 如何从子组件更新父状态变量

React-Native How to update parent state variable from child component

我在 react-native 中使用 Modal 呈现一个组件。因此,在子组件(作为模态显示在父组件之上的组件)中,我试图更新父组件的状态变量,但它抛出错误,如“'changeModalVisibility' is missing in props验证".

请帮我解决这个问题。

相关代码如下:

// 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**"
}

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

changeModalVisibility={this.changeModalVisibility}

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

子组件中的 onPress 属性应该是这样的:

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