我在本机反应中有两个组件,无法从子组件中关闭模态。
ListTrips-父级
ModalAddTrip-子项
ListTrips.js
import ModalAddTrip from './ModalAddTrip';
....
....
this.state = {
isModalAddTripVisible: false
}
....
handleDismissModalAddTrip = () => {
this.setState({ isModalAddTripVisible: false });
};
closeModal() {
this.refs.ModalAdd.handleDismissModalAddTrip();
}
....
<ModalAddTrip
ref="ModalAdd"
isVisible={this.state.isModalAddTripVisible}
onBackDropPress={this.handleDismissModalAddTrip}
closeModal={() => this.closeModal()}
onRequestClose={this.handleDismissModalAddTrip}
/>
ModalAddTrip.js
<Modal
isVisible={isVisible}
onBackdropPress={onBackDropPress}
closeModal={this.props.child}
>
<Button
style={{ fontSize: 18, color: 'white' }}
containerStyle={{
padding: 8,
marginLeft: 70,
}}
onPress={this.closeModal}
>
打开模态后,我无法关闭模态。我知道它与引用/属性有关,但是我已经花了好几个小时弄乱了,而且我什么都找不到。我正在尝试按照this.props.closeModal;
的方式将ref切换到child组件,但是它也不起作用。在ModalAddTrip中的函数中,但这也不起作用。
任何帮助将不胜感激。 谢谢
答案 0 :(得分:1)
//对我来说效果很好//
模态示例.JS
...
import Child from "./components/Child.js"
const ModalExample = () => {
const [modalVisible, setModalVisible] = useState(true)
return(
<Modal visible={ModalVisible}>
<Child closeModal={()=>setModalVisible(false)}/>
</Modal>
)
}
export default ModalExample
CHILD.JS
...
const Child = (closeModal) => {
render(
<Button title="close" onPress={closeModal.closeModal}/>
)
}
export default Child
答案 1 :(得分:0)
ModalAddTrip.js
_toggleModal = () =>
this.setState({ isVisible: !this.state.isVisible });
....
render() {
....
<Modal
isVisible={isVisible}
onBackdropPress={onBackDropPress}
>
<Button
style={{ fontSize: 18, color: 'white' }}
containerStyle={{
padding: 8,
marginLeft: 70,
}}
onPress={this._toggleModal} >
</Modal>
答案 2 :(得分:0)
这是我用来处理模态的解决方案。
export default class MyModal extends React.Component<Props, State>{
constructor(props: Props){
super(props);
this.state = {
visible: false,
}
}
// Use this method to toggle the modal !
toggleModal = () => {
this.setState({visible: !this.state.visible});
}
render(){
return(
<Modal
isVisible={this.state.visible}
hideModalContentWhileAnimating
onBackdropPress={() => {
this.toggleModal();
}}
useNativeDriver
>
<View style={{backgroundColor: "white", padding: 5}}>
</View>
</Modal>
);
}
}
如果我按下它,模态将关闭->它可以自行关闭。
现在可以通过父组件进行管理,只需从模态中获取引用即可:
<MyModal
ref={ref => {
this.myModal = ref;
}}
/>
您可以从父组件中切换它:
toggleMyModal = () => {
if(this.myModal){
this.myModal.toggleModal();
}
}
让我知道您是否可以使用它:)