尝试使用参考来访问子组件中的父函数



我有以下小吃:

https://snack.expo.io/@drc83/ref-close-modal

我想访问父母的功能。我试图通过参考通过该功能。当您单击"关闭模式"(在子组件中)时,应在父组件中调用函数coscemodalview并触发警报("关闭模式")。当前按下时我会遇到未定义的错误,请提前感谢任何帮助。

不确定为什么您需要参考来执行此操作,只是修改了您的代码,它会显示一个警报,如果您单击"确定",它将关闭模态

import * as React from 'react';
import { Text, View, StyleSheet, TouchableOpacity, Alert } from 'react-native';
import Modal from 'react-native-modal';
import StepOne from './components/StepOne';
class App extends React.Component {
  constructor(props: Object) {
    super(props);
    this.state = {
      isModalVisible: false,
    };
     this.modalView = React.createRef();
  }
  componentDidMount() {
    if (this.props.onRef) {
      this.props.onRef(this);
    }
  }
  componentWillUnmount() {
    if (this.props.onRef) {
      this.props.onRef(undefined);
    }
  }
  closeModalView = () => {
    Alert.alert(
  'Close Modal',
  'This will close the Modal',
  [
    {
      text: 'Cancel',
      onPress: () => console.log('Cancel Pressed'),
      style: 'cancel',
    },
    {text: 'OK', onPress: () => this.setState({ isModalVisible: false })},
  ],
  {cancelable: false},
);
  };
  showModalView = () => {
    this.setState({ isModalVisible: true });
//alert('true');
  };
  render() {
    return (
      <View style={{ paddingTop: 200 }}>
        <TouchableOpacity
          style={{ padding: 10, backgroundColor: 'yellow' }}
          onPress={() => this.showModalView()}>
          <Text>OPEN MODAL</Text>
        </TouchableOpacity>
        <Modal
          isVisible={this.state.isModalVisible}
          style={{
            bottom: 0,
            margin: 0,
            padding: 0,
            justifyContent: 'flex-end',
          }}
          onModalHide={this.closeModalView}
          onBackButtonPress={this.closeModal}
          backdropOpacity={0.5}>
          <StepOne closeModal={()=> this.closeModalView()} />
        </Modal>
      </View>
    );
  }
}
export default App;

在app.js中(在cospemotal中作为prop to stepone)替换

cockeModal = {()=> this.modalview.closemodalview()}

cockemodal = {this.closemodalview}

这应该有效。

在此.modalview上未定义函数cockemodalview。因此,孩子没有获得功能。

相关内容

  • 没有找到相关文章