将道具从Modal传递到其他组件反应导航
我使用react navigation。我有一个TabNavigator
。每个Tab
包含一个StackNavigator
。从一个StackNavigator
,可以打开Modal
。 Modal
在我点击某个Component
中的Button
时被打开。将道具从Modal传递到其他组件反应导航
export default class CallModalComponent extends Component {
constructor(props) {
super(props)
...
}
...
render() {
const { navigate } = this.props.navigation;
return (
<Button
....
onPress={() => navigate("Modal")}/>
中TabNav
注册屏幕<MyModal />
是有状态Component
。 关闭Modal
我需要的<MyModal />
传递到<CallModalComponent />
。
我遇到的问题是如何可以与react navigation
之间...我知道我可以使用redux
并通过global store
发送/检索它。但我不知道它是否可能只有react native
。 有什么建议吗?
编辑
我实现了代码的答案
export default class CallModalComponent extends Component {
constructor(props) {
super(props)
...
}
...
onModalDismis(childVar) {
console.log('modal is closing');
console.log(childVar);
}
render() {
const { navigate } = this.props.navigation;
return (
<Button
....
onPress={(childVar) => navigate("Modal", {onModalDismis: this.onModalDismis()})}/>
// Then in your modal component
componentWillUnmount() {
console.log('unmount');
this.props.navigation.state.params.onModalDismis('here we go');
}
下获取记录: 当Modal Component
安装我得到:
modal is closing
undefined
然后,当我真正关闭Modal
,我得到:
unmount
,然后错误:
Cannot read property of onModalDismiss of undefined.
我预计没什么登录的Modal
的安装。然后,当我关闭Modal
我预计
unmount
,modal is closing
和here we go
被记录。
@bennygenel非常接近。加了一点。
export default class CallModalComponent extends Component {
constructor(props) {
super(props)
...
}
...
onModalDismis(childVar) {
console.log('modal is closing');
console.log(childVar);
}
render() {
const { navigate } = this.props.navigation;
return (
<Button
....
onPress={() => navigate("Modal", {onModalDismis:(childVar) => this.onModalDismis(childVar)})}/>
// Then in your modal component
componentWillUnmount() {
this.props.navigation.state.params.onModalDismis("some var");
}
之所以使用的arrow function
是因为它binds()
这个https://medium.freecodecamp.org/react-binding-patterns-5-approaches-for-handling-this-92c651b5af56和它只被当onModalDismis()
被调用执行,而不是背景下呈现的<CallModalComponent/>
。 Difference in using functions in react-native
您可以在导航时将参数传递给屏幕。这允许您将功能发送到下一个屏幕,然后您可以在需要时启动它。更多详情here。
例
export default class CallModalComponent extends Component {
constructor(props) {
super(props)
...
}
...
onModalDismis() {
console.log('modal is closing');
}
render() {
const { navigate } = this.props.navigation;
return (
<Button
....
onPress={() => navigate("Modal", {onModalDismis: this.onModalDismis})}/>
// Then in your modal component
componentWillUnmount() {
this.props.navigation.state.params.onModalDismis();
}
你能否指点我可以阅读的文档? – Stophface
@Stophface已更新回答 – bennygenel
我认为你实现的代码错了。更新你的问题与你到目前为止,所以我可以有一个更好看 – bennygenel