gpt4 book ai didi

react-native - 将 screenProps 传递给选项卡导航器

转载 作者:行者123 更新时间:2023-12-01 22:12:34 25 4
gpt4 key购买 nike

背景

我有一个控制 2 个组件 View 的根组件。我有条件地渲染这些组件。

我将 screenProps 传递给这两个组件,这样我就可以从根组件中公开一个 function

当组件 1 被呈现时,它完美地采用了 screenProps。但是组件 2 实际上是由 tabNavigator 控制的。所以当它被加载时,它是 tabNavigator 中的默认组件,最终成为 Login

我想将 screenProps 传递给多个组件,或者换句话说,允许从 Login 组件中的根目录访问一个函数,该组件是通过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 的子级?

代码

调用 TabNavigator 的组件

const Public = props => (
<View style={styles.container}>
{/* <Header
headerStyle={StyleSheet.flatten(styles.headerColor)}
headerTitle="wunO"
/> */}
<BottomTabNav /* screenProps past here! */ />
</View>
);

LoginComponent,当从 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 }) }} />

公共(public)组件

<BottomTabNav screenProps={props.screenProps.login} />

登录组件

this.props.screenProps.login();

这会引发错误,

Cannot read property 'login of undefined

最佳答案

错误其实是对的。在您的登录组件 screenProps 中没有登录属性,因为您在公共(public)组件中传递了登录属性的值。

您可以像下面那样更改公共(public)组件,

<BottomTabNav screenProps={{ login: props.screenProps.login}} />

或者您可以像下面这样更改登录组件中的执行,

this.props.screenProps();

关于react-native - 将 screenProps 传递给选项卡导航器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47026936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com