将道具从布局传递给盖茨比中的孩子

luk*_*kas 6 reactjs gatsby

如何将道具从 Gatsby 布局传递给子级(例如 Header 组件)?

import React from "react";

export default ({ children }) => {
    return <div>{children()}</div>;
};
Run Code Online (Sandbox Code Playgroud)

我发现的资源使用以下格式:

{ props.children({ ...props, foo: true }) }
{ this.props.children({...this.props, updateLayoutFunction }) }
Run Code Online (Sandbox Code Playgroud)

但由于没有props,而只有孩子,我无法让它发挥作用。我试过这个,但它也不起作用:

{ children({ foo: true }) }
Run Code Online (Sandbox Code Playgroud)

在所有情况下,我都会收到此错误: TypeError: undefined is not an object (evaluating 'history.listen')

https://github.com/gatsbyjs/gatsby/issues/3412#event-1446894145 https://github.com/gatsbyjs/gatsby/issues/2112

Des*_*ian 6

但是有道具,你只是没有把它们传给孩子。

在您的布局文件中,而不是:

export default ({ children }) // ... etc
Run Code Online (Sandbox Code Playgroud)

export default (props) {
  const myOwnProperties = { foo: true };

  return (
    {props.children({ ...props, ...myOwnProperties })}
  );
}
Run Code Online (Sandbox Code Playgroud)

你看,道具会自动传递,直到你添加自己的道具。

  • 我收到“TypeError:props.children 不是函数” (3认同)