Tab.Navigator组件只能将Tab.Screen组件作为直接子组件。
在Typescript中,有没有办法将Tab.Screen Type转换为TabButton函数??
const App = () => {
return (
<NavigationContainer>
<Tab.Navigator tabBarOptions={{
...>
<Tab.Screen name={'name1'} component={component1} />
<Tab.Screen name={'Add Photos'} component={FeedScreen}
options={{
tabBarButton: ...
/>
<TabButton title={'Setting'} component={SettingScreen} imageSrc={'./icons/accountDark.png'}/>
}
以下是我尝试做的
type TabButtonProps = {
title: string,
component: any,
imageSrc: string,
}
const TabButton = ({title, component, imageSrc}: TabButtonProps) => {
return (
<Tab.Screen name={title} component={component} options={{
tabBarIcon: ({focused}) => (
<View style={{alignItems: 'center', justifyContent: 'center', top: 10}}>
<Image source={imageSrc as ImageSourcePropType}
resizeMode='contain'
style={{width: 25, height: 25, tintColor: focused ? '#999999' : '#dddddd'}}
/>
</View>
)}}/>
)
}
我有:
Error: A navigator can only contain 'Screen' components as its direct children (found 'TabButton'). To render this component in the navigator, pass it in the 'component' prop to 'Screen'.
这与TypeScript无关,因此强制转换无法解决此问题。您可以使用组件生成而不是包装组件:
const createTabButton = ({title, component, imageSrc}: TabButtonProps) => {
return (
<Tab.Screen name={title} component={component} options={{
tabBarIcon: ({focused}) => (
<View style={{alignItems: 'center', justifyContent: 'center', top: 10}}>
<Image source={imageSrc as ImageSourcePropType}
resizeMode='contain'
style={{width: 25, height: 25, tintColor: focused ? '#999999' : '#dddddd'}}
/>
</View>
)}}/>
)
}
...
const App = () => {
return (
<NavigationContainer>
<Tab.Navigator tabBarOptions={{
...>
<Tab.Screen name={'name1'} component={component1} />
<Tab.Screen name={'Add Photos'} component={FeedScreen}
options={{
tabBarButton: ...
/>
{createTabButton({title: 'Setting', component: SettingScreen, imageSrc:'./icons/accountDark.png'})}
<NavigationContainer/>
}
您还可以";技巧";通过设置显示名称来显示库:
TabButton.displayName = 'Tab.Screen'