[英]How do I conditionally render the color of my component based on the prop?
[英]How do I conditionally render a component in Gatsby based on specific page?
我正在 Gatsby 上建立一个网站,我希望能够根据我所在的页面有条件地呈现一个组件。 例如,在页脚中我有一个组件,我不希望它出现在“我们的内容”页面上,但对于网站的其余部分是。
我尝试这样做,这奏效了,但是在运行构建后给我一个错误提示: "window" is not available during server side rendering.
{ window.location.pathname !== '/ourcontent'
? <MyComponent />
: null
}
我使用功能组件工作。
我将如何能够实现这一目标? 任何帮助将不胜感激! 非常感谢您的先进!
在任何 Gatsby 页面组件上,您都应该有一个location
属性。 然后你可以使用props.location.pathname
获取路径名。 很确定这也适用于服务器端渲染(您的构建)。
实现它的最简单和最简单(最干净)的方法是使用 Gatsby 提供的内置props
。 正如您在他们的文档中所见,它公开了一个location
prop
,其中包含所有需要的信息。 当然,因为它不是一个全局的浏览器对象,比如window
或document
,它在服务器端渲染期间以及运行时期间都是可用的。
您可以简单地:
import React from "react"
import { graphql } from "gatsby"
const Component = ({ location, data }) => {
return location.pathname !== 'ourcontent' ? <MyComponent /> : null
}
export default Component
您可以通过使用location.pathname !== 'ourcontent' && <MyComponent />
删除三元条件来改进它,不需要返回null
。
您也可以使用@reach/router
。 这是一个非常简单的例子。
import { Location } from '@reach/router'
const IndexPage = () => (
<Layout>
<h1>Hi people</h1>
<Location>
{({ location }) => {
console.log(location)
if (location === '/') return <p>You are on the homepage {location.pathname}</p>
return <h1> you are not on the homepage </h1>
}}
</Location>
</Layout>
)
export default IndexPage
此代码和框显示了@reach/router
和location.pathname
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.