简体   繁体   English

如何使用 react-router v6 中的元素传递道具?

[英]How to pass props using element in react-router v6?

I'm trying to reuse my MainSection component for two different purposes (single story and all stories).我正在尝试将 MainSection 组件用于两个不同的目的(单个故事和所有故事)。 To effect this, I want to pass in a property, home, in the Routes that go to those renderings of that component.为了实现这一点,我想将 go 路由中的属性 home 传递给该组件的那些渲染。 Home is true or false, and I want to render the MainSection component based on that boolean. Home 是真还是假,我想根据那个 boolean 来渲染 MainSection 组件。 However, I home keeps being undefined when MainSection gets rendered.但是,当 MainSection 被渲染时,我的家一直未定义。 The link and route are updating the URL, but not rendering with the props I want.链接和路线正在更新 URL,但没有使用我想要的道具进行渲染。 Am I doing something wrong?难道我做错了什么?

Here are my routes:这是我的路线:

function Routes(){
  return(
    <Switch>
      <Route path="/"  element={<MainSection home={true} />} />
      <Route path="/story" element={ <MainSection home={false} />} />
    </Switch>
  )
}

and here is the code for my MainSection component:这是我的 MainSection 组件的代码:

function MainSection({ home }){
  console.log(home)
  return(
    <div className="main-section">
      <BigPicture home={ home }/>
      <Quotes home={ home }/>
    </div>
  )
}

The console log keeps returning undefined.控制台日志不断返回未定义。

Thanks!谢谢!

Since in the question title you state you are using react-router-dom version 6 I'll answer against that.由于在问题标题中您 state 您使用的是react-router-dom版本 6,因此我将对此进行回答。 V6 doesn't export a Switch component, it was replaced by a Routes component. V6 没有导出Switch组件,它被替换为Routes组件。 Swap the Switch for the Routes component and rename your Routes component to something else to avoid the name collision.交换Routes组件的Switch并将您的Routes组件重命名为其他名称以避免名称冲突。

function MainRoutes(){
  return(
    <Routes>
      <Route path="/" element={<MainSection home />} />
      <Route path="/story" element={<MainSection />} />
    </Routes>
  )
}

From here the home prop should either be treated as truthy/falsey.从这里开始, home道具应该被视为真/假。 You can double-bang it to coerce it to a strict boolean value.您可以对其进行双重打击以将其强制为严格的 boolean 值。 Passing home through to children components should also work without issue.home传递给子组件也应该可以正常工作。

function MainSection({ home }) {
  React.useEffect(() => {
    console.log(!!home);
  }, [home]);

  return(
    <div className="main-section">
      <BigPicture home={home} />
      <Quotes home={home} />
    </div>
  )
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM