从孩子到父母的道具反应导航 [英] Pass props from child to parent react navigation
问题描述
我正在使用 react-navigation
。我将 props
从 react-native组件
传递到模式
来自 react-navigation
,这是在点击时打开的。
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: ..., ...})}
..../>
)
}
}
<$ c $里面c> modal 我访问 goBack()
函数,该函数关闭模态
,以及当道具
通过 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>
)
}
}
我想知道的是,是否可以传递道具
down 从模态
到 SomeComp
,没有使用终极版
。
在普通 react-native父子组件中
我会用一个简单的回调
来做。但是,这在这里不起作用,因为模态
是在路由器
中定义的,因此完全独立于 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...
推荐答案
在<$ c $上将道具传递给父组件的确有一个简单的解决方案c> goBack()。
你可以在调用 goBack之前将一个额外的prop包含函数传递给Modal )
或 componentWillUnmount
你可以调用该函数。
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>
)
}
}
这篇关于从孩子到父母的道具反应导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!