将 screenProps 传递给选项卡导航器
背景
我有一个根组件来控制 2 个组件的视图.我有条件地渲染这些组件.
I have a root component that controls the views of 2 components. I am conditionally rendering these components.
我将 screenProps
传递给这 2 个组件,以便我可以从根组件公开一个 function
.
I am passing screenProps
to these 2 components so I can expose a function
from the root components.
当组件 1 被渲染时,它完美地采用了 screenProps
.但是组件 2 实际上是由 tabNavigator
控制的.所以当它被加载时,它是 tabNavigator
中的默认组件,最终是 Login
.
When component 1 is rendered it takes the screenProps
perfectly. But component 2 is actually controlled by a tabNavigator
. So when it is loaded, it is the default component in the tabNavigator
which ends up being Login
.
我想将 screenProps
传递给多个组件,或者换句话说,在 Login
组件中从根访问一个函数,这是一个通过加载的组件TabNavigator
.
I want to pass the screenProps
down multiple components or in other words give access to a function from root in the Login
component, which is a component that is loaded through the TabNavigator
.
示例
<Secure screenProps={{ login: () => this.setState:({ secure: false }) }} />
<Public screenProps={{ login: () => this.setState:({ secure: true }) }} />
Secure takes the component fine. But the screenProps is called inside of the actual Secure component. The Public component has a TabNavigator. So when I pass screenProps to Public the components loaded via the TabNavigator do not have access to the screen props.
问题
如何将 screenProps
传递给通过 TabNavigator
加载的 Public
的子级?
How do I pass screenProps
to the children of Public
which are loaded through a TabNavigator
?
代码
调用TabNavigator
const Public = props => (
<View style={styles.container}>
{/* <Header
headerStyle={StyleSheet.flatten(styles.headerColor)}
headerTitle="wunO"
/> */}
<BottomTabNav /* screenProps past here! */ />
</View>
);
LoginComponent
当从 PublicComponent
单击选项卡时加载.
LoginComponent
which is loaded when tab is clicked from the PublicComponent
.
async getToken() {
try {
const tokenKey = 'WUNO-TOKEN';
const token = await AsyncStorage.getItem(tokenKey, (err) => {
if (err) {
throw err;
}
this.props.screenProps.login();
});
return token;
} catch (e) {
throw e;
}
}
一起来,
主要组件
<Public screenProps={{ login: () => this.setState({ secure: true }) }} />
公共组件
<BottomTabNav screenProps={props.screenProps.login} />
登录组件
this.props.screenProps.login();
这会引发错误,
无法读取属性 'login of undefined
Cannot read property 'login of undefined
错误其实是对的.在您的登录组件 screenProps
中没有登录属性,因为您在公共组件中传递了登录属性的值.
The error is actually right. In your Login Component screenProps
doesn't have a login property because you pass the value of login property in Public Component.
您可以更改公共组件,如下所示,
You can either change Public component like below,
<BottomTabNav screenProps={{ login: props.screenProps.login}} />
或者您可以像下面那样在登录组件中更改执行,
or you can change execution in Login Component like below,
this.props.screenProps();