[英]React - sending props to component
I'm using React or Gatsby for a static website. 我将React或Gatsby用于静态网站。 A subpages need to send an prop or a variable(bool) to the main layout component, to determinme if we show a Hero image or not.
子页面需要向主布局组件发送一个prop或一个变量(布尔),以确定我们是否显示Hero图像。
I got the following code (simplified) for the page: 我为页面得到了以下代码(简化):
import React from 'react'
import { graphql } from 'gatsby'
import Layout from '../components/layout'
import dividerIcon from '../images/hair-cut-tool.svg'
const IndexPage = ({ data }) => (
<Layout showHero={true}>
<div className="divider-wrapper">
<div className="divider">
<img alt="divider" src={dividerIcon} />
</div>
</div>
</Layout>
)
export default IndexPage
How can I "get" the prop in may Layout.js? 如何在may Layout.js中“获取”道具?
I'm sending it with "" but I have no idea, how to get this variable and use it. 我用“”发送它,但我不知道如何获取该变量并使用它。
As for right now the Layout.js looks like this: 至于现在的Layout.js看起来像这样:
const Layout = ({ children }) => (
<StaticQuery
query={graphql`
query SiteTitleQuery {
site {
siteMetadata {
title
}
}
heroImgLogo: file(relativePath: { eq: "logo.png" }) {
childImageSharp {
fixed(width: 300) {
...GatsbyImageSharpFixed_withWebp_noBase64
}
}
}
}
`}
render={data => (
<>
<div className="site">
{(children.showHero) ?
<Hero logoImg={data.heroImgLogo.childImageSharp.fixed} />
:
null }
<div className="site-content container">{children}</div>
</div>
</>
)}
/>
);
Layout.propTypes = {
children: PropTypes.node.isRequired,
}
export default Layout
yet again, simplified. 再次简化。
I tried to children.showHero but it wasn't the right approach, I guess. 我尝试了children.showHero,但是我猜这不是正确的方法。
Any hints? 有什么提示吗?
You can destructure it alongside children: 您可以将其与子级一起分解:
const Layout = ({ children, showHero }) => (
Be sure to replace children.showHero
with just showHero
. 确保仅用
showHero
替换children.showHero
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.