首页 > 解决方案 > 反应导航中的 contentComponent 上未定义道具

问题描述

我正在尝试在我的抽屉上添加一个注销按钮,所以我使用 contentComponent 来单独自定义创建注销(而不是其他抽屉菜单)。所以,我创建了一个类并试图接收 DrawerItems 但它说没有定义道具。请帮忙。

我的代码自定义组件:

 class DrawerComponent extends Component {
constructor(props) {
    super(props)
    console.log(this.props)
  }

render () {
    return (
        <View style={{flex:1}}>
            <SafeAreaView forceInset={{ top: 'always', horizontal: 'never' }}>
                <DrawerItems {props.children} />
                <TouchableOpacity onPress={() => console.log("Pressed")}>
                    <Text>
                    Logout
                    </Text>
                </TouchableOpacity>
            </SafeAreaView>
        </View>
    );
  }
 }; 

我的抽屉选项:

 const DrawerNavigator = createDrawerNavigator({
Dashboard: {
  screen: AppStackNavigator,
  navigationOptions: {
    drawerLabel: "Home",
  }
},
Training: {
  screen: Training,
  navigationOptions: {
    drawerLabel: "Training"
  }
},
RoutePlan: {
  screen: RouteCalendar,
  navigationOptions: {
    drawerLabel: "Route Plan"
  }
},
Logout: {
  screen: StoreList,
  navigationOptions: {
    drawerLabel: "Logout"
  }
}
},
{
contentOptions: {
  activeTintColor: '#127CC1',
},
contentComponent: props => <DrawerComponent {...props}/>,
drawerOpenRoute: 'DrawerOpen',
drawerCloseRoute: 'DrawerClose',
drawerToggleRoute: 'DrawerToggle',
navigationOptions : ({navigation}) => {
  const { routeName } = navigation.state.routes[navigation.state.index];
  const headerTitle = routeName;
  return {
      headerTitle,
      headerLeft: (
        <Icon name="md-menu" style={{ marginLeft: 10 }} 
        onPress={() => navigation.toggleDrawer()}
        />
      )
    }
  }
}
);

在我的 customComponent 页面上出现错误。请帮助我度过难关!

标签: javascriptreact-nativereact-native-navigation

解决方案


在您的render方法中DrawerComponent,您正在调用props.children. 在那种情况下,props还没有在 render 方法中定义。您可以let props = this.props在 render 方法的开头使用一行来定义它,或者只是调用this.props而不是裸props.

如果您改用功能组件,则不需要从 获取propsthis而是将其作为功能组件的参数:

function FooComponent(props){
  return (<div style={{color:"#F00"}}>props.children</div>)
}

ReactDOM.render(<FooComponent><em>Hi!</em></FooComponent>, targetElement)

推荐阅读