wee*_*urt 25 parameter-passing reactjs react-native react-redux react-props
这是我在 StackOverflow 上的第一篇文章,如果我没有遵循正确的格式,我深表歉意。
我正在构建我的第一个应用程序,tab navigator from React Navigation v 5.x并且在将道具从一个屏幕传递到另一个屏幕时遇到了一个大问题
我想要实现的是:
我已经尝试过这个(我没有设置道具传递下去),这个(react-navigation 的弃用版本)和这个(react-navigation 的旧版本)。
和 Redux,但当前版本的 React 导航没有可用的示例。
我已经对此束手无策了,真的需要逐步了解如何实现这一目标。这是我想要做的粗略草图:
我想到的方法是通过回调将父状态作为道具发送下来,但是我找不到通过最新版本的反应导航中的屏幕组件发送道具的方法......
这是我的导航设置:
const Tab = createBottomTabNavigator()
export default class MyApp extends Component{
constructor(props) {
super(props);
}
render(){
return (
<NavigationContainer>
<Tab.Navigator
screenOptions={({ route }) => ({
tabBarIcon: ({ focused, color, size }) => {
let iconName;
if (route.name === 'My tests') {
iconName = focused ? 'ios-list-box' : 'ios-list';
} else if (route.name === 'Testroom') {
iconName = focused ? 'ios-body' : 'ios-body';
}
return <Ionicons name={iconName} size={size} color={color} />;
},
})}
tabBarOptions={{
activeTintColor: 'tomato',
inactiveTintColor: 'gray',
}}>
<Tab.Screen name="My tests" component={MyTests}/> //This is where I want to send props
<Tab.Screen name="Testroom" component={TestRoom} /> //This is where I want to send props
</Tab.Navigator>
</NavigationContainer>
)
}
}
Run Code Online (Sandbox Code Playgroud)
我读过这个,但对我来说没有意义。这如何适合组件树?什么去哪里?请帮忙!
小智 44
您可以使用属性“children”来传递元素类型 jsx,而不是属性“component”,这是从 react-native 推荐的。
通过这种方式,您可以将道具传递给组件示例:
<tab.Screen
name="home"
children={()=><ComponentName propName={propValue}/>}
/>
Run Code Online (Sandbox Code Playgroud)
使用 '()=>' 是必要的,因为属性 children 需要一个返回 jsx 元素的函数,它是函数式的。
Jos*_*igo 17
反应导航版本 5+
<Tab.Screen name="Work" component={Works} initialParams={{ age: 45 }} />
Run Code Online (Sandbox Code Playgroud)
可以使用Works组件上的 props 进行访问。
Ris*_*hav 11
查看代码注释中的答案。
<Tab.Screen
name="AdminTab"
children={() => <AdminPage userData={this.props.userSettings} />}
// component={() => <AdminPage userData={this.props.userSettings} />} <<<---- Although this will work but passing an inline function will cause the component state to be lost on re-render and cause perf issues since it's re-created every render. You can pass the function as children to 'Screen' instead to achieve the desired behaviour. You can safely remove the component attribute post adding children.
/>
Run Code Online (Sandbox Code Playgroud)
看起来您正在为屏幕“AdminTab”(例如
component={() => <SomeComponent />})的“component”道具传递一个内联函数。传递内联函数将导致组件状态在重新渲染时丢失并导致性能问题,因为它会在每次渲染时重新创建。您可以将函数作为子项传递给“屏幕”,以实现所需的行为。
为了将 props 发送到<MyTests />组件,请在内部<Tab.Screen />:
<Tab.Screen name="My tests">
{() => <MyTests myPropsName={myPropsValue} />}
</Tab.Screen>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
21085 次 |
| 最近记录: |