【问题标题】:Is it possible to pass my own props when using @reach/router with Gatsby?使用 @reach/router 和 Gatsby 时是否可以传递我自己的道具?
【发布时间】:2020-08-08 12:06:59
【问题描述】:

我正在尝试传递我自己的自定义道具(函数、对象 ..etc),但它们没有传递,当我在没有 gatsby 的情况下尝试 @reach/router 时它可以正常工作。

我的 app.js:

      <Router basepath="">
        <Welcome path="" />
        <OtherComponent
          path="/comppath"
          myprop="prop data"
        />
      </Router>

我的 OtherComponent.js

export default function OtherComponent(props){
    return (
        <div>
            <h1>My Component</h1>
            {props.myprop}
        </div>
    );
}

组件渲染良好,但我的道具没有通过,当我控制台记录道具时,我只得到路径、位置、pageContext 和导航方法..etc,但没有得到我的道具

旁注:我正在使用 gatsby 的 gatsby-plugin-create-client-paths

【问题讨论】:

    标签: gatsby reach-router gatsby-plugin


    【解决方案1】:

    使用 &lt;Link&gt; 组件(由 React 的 @reach/router 扩展),您可以传递一个 state 对象,该对象可以包含您想要的任何内容。

    &lt;Link&gt; 组件确实是@reach/router 的包装器,它为 Gatsby 添加了有用的增强功能。所有道具都传递给@reach/router&lt;Link&gt; 组件。应用于您的代码:

    <Link
      to={`/comppath`}
      state={{ myProp: 'hello'}}
    >
    

    然后在您的OtherComponent 中,您需要检查:location.state.myProp 将具有hello 作为值。

    要传递props,您只需为您的对象更改hello

      state={{ myProp: props }}
    

    您可以在Gatsby Link API documentation查看更多信息。

    【讨论】:

    • 嘿,谢谢你的回答,但是如果我想在本页的最后一个示例reach.tech/router/api/RouteComponent 中将道具直接传递给组件怎么办?
    • 您可以为您的props 对象更改hello 字符串
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-08
    • 2018-11-20
    • 1970-01-01
    • 2016-04-14
    • 2019-04-07
    • 2022-01-12
    • 2018-04-27
    相关资源
    最近更新 更多