Pass props from layout to children in Gatsby

孤人 提交于 2019-12-12 12:25:31

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!