问题描述
如何将道具从Gatsby布局传递给子级(例如Header组件)?
How can I pass props from Gatsby layout to children (for example a Header component)?
import React from "react";
export default ({ children }) => {
return <div>{children()}</div>;
};
我发现的资源使用以下格式:
The resources I found use the following format:
{ props.children({ ...props, foo: true }) }
{ this.props.children({...this.props, updateLayoutFunction }) }
但是因为没有props
,只有孩子,所以我无法使用它.我试过了,但是也没用:
But since there is no props
, but only children, I can't get this to work. I tried this, but it also didn't work:
{ children({ foo: true }) }
在所有情况下,我都会收到以下错误:TypeError: undefined is not an object (evaluating 'history.listen')
In all cases, I get this error: 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
推荐答案
但是有道具,您只是没有将它们传递给孩子.
But there are props, you're just not passing them to children.
在您的布局文件中,而不是:
In your layout file, instead of:
export default ({ children }) // ... etc
做
export default (props) {
const myOwnProperties = { foo: true };
return (
{props.children({ ...props, ...myOwnProperties })}
);
}
您会看到,道具会自动传递,直到您添加自己的道具为止.
You see, the props are passed automatically until you add your own.
这篇关于将道具从布局传递给盖茨比的孩子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!