我有以下小吃:
https://snack.expo.io/@drc83/ref-close-modal
我想从父母访问该功能。我试图通过ref传递函数。当您单击关闭模式(在子组件中)时,这应该调用父组件中的函数closeModalView并触发警报('关闭模态')。目前按下时我得到未定义的错误,任何帮助解决将提前感谢,谢谢。
不知道为什么你需要refs这样做,只是修改你的代码,这工作,它会显示一个警报,如果你点击确定它将关闭模态
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中(其中closeModal作为支持传递给StepOne)替换
closeModal = {()=> this.modalView.closeModalView()}
同
closeModal = {this.closeModalView}
这应该工作。
函数closeModalView未在this.modalView上定义。因此,孩子没有得到这个功能。