与盖茨比一起使用@reach/router时,有可能传递我自己的道具吗



我试图传递我自己的自定义道具(函数、对象等(,但它们没有传递,当我尝试在没有gatsby的情况下使用@reach/router时,效果很好。

我的应用程序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和导航方法。。等等,但不是我的道具

附带说明:我正在使用gatsby的gatsby插件创建客户端路径

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

<Link>组件实际上是@reach/router的包装器,它添加了Gatsby特有的有用增强。所有道具都传递到@reach/router<Link>组件。应用于您的代码:

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

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

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

state={{ myProp: props }}

您可以在Gatsby Link API文档中查看更多信息。

相关内容

最新更新