问题
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 }) }
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 }) }
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
回答1:
But there are props, you're just not passing them to children.
In your layout file, instead of:
export default ({ children }) // ... etc
do
export default (props) {
const myOwnProperties = { foo: true };
return (
{props.children({ ...props, ...myOwnProperties })}
);
}
You see, the props are passed automatically until you add your own.
来源:https://stackoverflow.com/questions/48725557/pass-props-from-layout-to-children-in-gatsby