问题描述
我正在使用 react-navigation
.我将 props
从 react-native 组件
传递到 react-navigation
的 modal
点按.
I am using react-navigation
. I am passing props
from a react-native component
to the modal
from react-navigation
which is opened on a tap.
export default class SomeComp extends Component {
...
render() {
const { navigate } = this.props;
return (
<TouchableOpacity
onPress={navigate("Modal", {data: ..., ...})}
..../>
)
}
}
在 modal
中,我访问了 goBack()
函数,它关闭了 modal
以及 props
> 通过 SomeComp
Inside the modal
I access the goBack()
function which closes the modal
, as well as the props
passed through SomeComp
export default class Modal extends Component {
...
render() {
const { data, ... } = this.props.navigation.state.params;
const { goBack } = this.props.navigation;
return (
<View>
<TouchableOpacity
onPress={goBack()}
..../>
<Text>
{data, ...}
</Text>
</View>
)
}
}
我想知道的是,是否可以将 props
down 从 Modal
传递到 SomeComp
,没有使用redux
.在普通"react-native 父子组件
中,我会用一个简单的callback
来做到这一点.但是,这在这里不起作用,因为 modal
是在 router
中定义的,因此完全独立于 SomeComp
.它只是从那里调用...
What I wonder is, whether its possible or not to pass props
down from Modal
to SomeComp
, without using redux
.In a "normal" react-native parent-child component
I would do that with a simple callback
. However, that does not work here, because the modal
is defined in the router
, hence, completely independent from SomeComp
. Its only called from there...
推荐答案
在 goBack()
上将 props 传回父组件有一个非常简单的解决方案.
There is really simple solution to pass back props to parent component on goBack()
.
您可以在调用 goBack()
之前或在 componentWillUnmount
中将包含函数的额外道具传递给 Modal,您可以调用该函数.
You can pass an extra prop containing function to Modal and right before calling goBack()
or in componentWillUnmount
you can call that function.
示例
export default class SomeComp extends Component {
...
onGoBack = (someDataFromModal) => {
console.log(someDataFromModal);
}
render() {
const { navigate } = this.props;
return (
<TouchableOpacity
onPress={navigate("Modal", {data: ..., ..., onGoBack: this.onGoBack})}
..../>
)
}
}
export default class Modal extends Component {
...
componentWillUnmount() {
if(this.props.navigation.state.params.onGoBack) {
this.props.navigation.state.params.onGoBack('I fired from Modal!');
}
}
render() {
const { data, ... } = this.props.navigation.state.params;
const { goBack } = this.props.navigation;
return (
<View>
<TouchableOpacity
onPress={goBack()}
..../>
<Text>
{data, ...}
</Text>
</View>
)
}
}
这篇关于将道具从子级传递给父级反应导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!