【问题标题】:Pass props from layout to children in Gatsby在盖茨比中将道具从布局传递给孩子
【发布时间】:2018-02-10 21:05:26
【问题描述】:

如何将道具从 Gatsby 布局传递给子级(例如 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({ 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

【问题讨论】:

    标签: reactjs gatsby


    【解决方案1】:

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

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

    export default ({ children }) // ... etc
    

    export default (props) {
      const myOwnProperties = { foo: true };
    
      return (
        {props.children({ ...props, ...myOwnProperties })}
      );
    }
    

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

    【讨论】:

    • 我收到“TypeError:props.children 不是函数”
    猜你喜欢
    • 2020-02-20
    • 2021-02-13
    • 2019-10-16
    • 2018-08-25
    • 2020-08-08
    • 1970-01-01
    • 2018-04-09
    • 2016-03-19
    • 1970-01-01
    相关资源
    最近更新 更多