eslint 抛出错误:在渲染期间不要定义组件

问题描述 投票:0回答:1

我正在尝试渲染抽屉导航中的图标,但 eslint 抛出错误:在渲染期间不要定义组件。

不要在渲染期间定义组件。 React 将在每次渲染时看到一个新的组件类型,并销毁整个子树的 DOM 节点和状态 (https://reactjs.org/docs/reconciliation.html#elements-of- Different-types)。相反,将此组件定义移出父组件“DrawerLayout”并将数据作为 props 传递。如果你想允许在 props 中创建组件,请将 allowedAsProps 选项设置为 true.eslintreact/no-unstable-nested-components

      <Drawer
        drawerContent={CustomDrawerContent}
        screenOptions={{
          headerStyle: {
            backgroundColor: '#171630',
          },
          headerTintColor: '#fff',
          drawerHideStatusBarOnOpen: true,
          drawerActiveBackgroundColor: '#171630',
          drawerActiveTintColor: '#fff',
          drawerLabelStyle: { marginLeft: -20 },
          headerRight: () => <HeaderRight onLogout={onLogout} />, // at this line I am getting above error by eslint
        }}
      >

我尝试了很多方法来解决这个问题,但我只得到我可以按照规则禁用 eslint。 但我想知道为什么它会抛出错误。 是否可以在不禁用 eslint 的情况下进行?

react-native eslint react-native-navigation eslint-config-airbnb react-native-drawer
1个回答
1
投票

我知道了答案,我创建了单独的 util 文件,然后像这样重新定义了组件

export const HeaderRight = (action, lib, icon, size, color) => (
  <View style={{ marginLeft: 15, marginRight: 15 }}>
    <TouchableOpacity onPress={action}>{IconComponent(lib, icon, size, color)}</TouchableOpacity>
  </View>
);

为了使用它,我将其用作函数而不是组件

HeaderLeft(action, 'FontAwesome', 'star', 20, 'red');
© www.soinside.com 2019 - 2024. All rights reserved.