【问题标题】:React native and React router native v6React native 和 React router native v6
【发布时间】:2022-01-21 06:32:03
【问题描述】:

我有:react-router-native: 6.2.1。

我有一个组件: App.js:

const App = () => (
  <NativeRouter>
    <RoutesView />
  </NativeRouter>
)

RoutesView.js:

const RoutesView = () => (
  <Routes>
    <Route path="/" element={<Menu />}>
      <Route path="/add" element={<AddPurchases />} />
    </Route>
  </Routes>
)

和 Menu.js:

const Menu = () => (
  <View>
    <Text>Welcome!</Text>
    <Link to="/profile">Visit your profile</Link>
  </View>
)

React 返回错误:

React.Children.only 期望接收单个 React 元素子元素。

当我删除 &lt;Link to="/profile"&gt;Visit your profile&lt;/Link&gt; 时,应用程序工作正常。为什么我不能在&lt;Route /&gt; 中使用&lt;Link /&gt;? 我该如何解决?

【问题讨论】:

  • 为什么在 RoutesView 中你要在另一个 Route 中创建一个 Route?
  • @RhettHarrison 我正在使用这个docs。错了吗?
  • @RhettHarrison 这就是您构建嵌套路由和 UI 的方式。
  • 这个错误归咎于哪个组件?您没有在Route 中使用Link,而是在View 中使用Link。 View 是不是说它只需要一个子元素?
  • @DrewReese 我不知道是不是View 的错。但是现在我将Menu 组件更改为:const Menu = () =&gt; &lt;Link to="/profile"&gt;Visit your profile&lt;/Link&gt; 并从RoutesView 中删除了&lt;Route path="/" element={&lt;Menu /&gt;}&gt; 并将Menu 移动到App,但仍然出现此错误

标签: reactjs react-native react-router


【解决方案1】:

试试这个:

export const Menu = () => (
    <View>
      <div className="wrapper">
        <Text>Welcome!</Text>
        <Link to="/profile">Visit your profile</Link>
      </div>
    </View>
);

我不确定 View 做了什么,但我知道 React 喜欢只返回一个元素,所以我将它包装在一个 div 元素中

【讨论】:

  • 它不工作。我仍然有同样的错误
  • 错误出现在哪个组件上? @michal
  • View 是单个元素并且已经包装了返回的内容。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多