在 Gatsby 中将道具从布局传递到 children
Pass props from layout to children in Gatsby
如何将 props 从 Gatsby 布局传递到 children(例如 Header 组件)?
import React from "react";
export default ({ children }) => {
return <div>{children()}</div>;
};
我找到的资源使用以下格式:
{ props.children({ ...props, foo: true }) }
{ this.props.children({...this.props, updateLayoutFunction }) }
但是因为没有 props
,只有 children,我无法让它工作。我试过了,但还是没用:
{ children({ foo: true }) }
在所有情况下,我都会收到此错误: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
但是有道具,你只是没有将它们传递给 children。
在您的布局文件中,而不是:
export default ({ children }) // ... etc
做
export default (props) {
const myOwnProperties = { foo: true };
return (
{props.children({ ...props, ...myOwnProperties })}
);
}
你看,道具会自动传递,直到你添加自己的道具。
如何将 props 从 Gatsby 布局传递到 children(例如 Header 组件)?
import React from "react";
export default ({ children }) => {
return <div>{children()}</div>;
};
我找到的资源使用以下格式:
{ props.children({ ...props, foo: true }) }
{ this.props.children({...this.props, updateLayoutFunction }) }
但是因为没有 props
,只有 children,我无法让它工作。我试过了,但还是没用:
{ children({ foo: true }) }
在所有情况下,我都会收到此错误: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
但是有道具,你只是没有将它们传递给 children。
在您的布局文件中,而不是:
export default ({ children }) // ... etc
做
export default (props) {
const myOwnProperties = { foo: true };
return (
{props.children({ ...props, ...myOwnProperties })}
);
}
你看,道具会自动传递,直到你添加自己的道具。