根据页面向头部添加react组件

时间:2018-06-01 18:32:17

标签: javascript reactjs children gatsby

除了我网站的两个页面外,我希望标题包含两个按钮。如何使标题知道这一点,以便它在需要时包含按钮,而不包括其他两个页面。我正在使用React和Gatsby

我可以通过向组件添加if语句来实现此目的吗?如果是这样,我不确定如何超越这一步。

  const isHomepage = pathname == `/`
  const isContact = pathname == `/contact/`
  let styles = {}
  if (isHomepage) {

    }
  } else if (isContact) {



     } else {
  }

这是我的标题代码:

import React from 'react'
import Link from 'gatsby-link'
import colors from '../utils/colors'

const Header = ({ siteTitle }) => (
  <div
    style={{
      background: colors.white,
      marginBottom: '1.45rem',
      borderBottom: '1px solid',
      borderBottomColor: colors.green,
      height: '3rem',
      top: 0,
      left: 0,
      width: '100%',
      position: 'fixed',
    }}
  >
    <div
      style={{
        paddingLeft: 20,
        paddingRight: 20,
        marginLeft: 'auto',
        marginRight: 'auto',
        maxWidth: 960,
      }}
    >
      <div
        style={{
          display: 'flex',
          flexDirection: 'row',
          alignItems: 'center',
          height: 53,
        }}>
        <h3 style={{
          margin: 0,
        }}>
        <Link
          to="/"
          style={{
            color: colors.green,
            textDecoration: 'none',
            fontWeight: 450,
          }}
        >
          {siteTitle}
        </Link>
      </h3>
        </div>
    </div>
  </div>
)

export default Header

1 个答案:

答案 0 :(得分:3)

使用基于location.pathname的条件渲染

{['/path1', '/path2'].indexOf(location.pathname) === -1 && (
   <button>1<button>
   <button>2<button>
)}

import React from 'react'
import Link from 'gatsby-link'
import colors from '../utils/colors'

const Header = ({ siteTitle }) => (
  <div
    style={{
      background: colors.white,
      marginBottom: '1.45rem',
      borderBottom: '1px solid',
      borderBottomColor: colors.green,
      height: '3rem',
      top: 0,
      left: 0,
      width: '100%',
      position: 'fixed',
    }}
  >
    <div
      style={{
        paddingLeft: 20,
        paddingRight: 20,
        marginLeft: 'auto',
        marginRight: 'auto',
        maxWidth: 960,
      }}
    >
      <div
        style={{
          display: 'flex',
          flexDirection: 'row',
          alignItems: 'center',
          height: 53,
        }}>
        <h3 style={{
          margin: 0,
        }}>
        <Link
          to="/"
          style={{
            color: colors.green,
            textDecoration: 'none',
            fontWeight: 450,
          }}
        >
          {siteTitle}
        </Link>
        {['/path1', '/path2'].indexOf(location.pathname) === -1 && (
          <button>1<button>
          <button>2<button>
        )}
      </h3>
        </div>
    </div>
  </div>
)

export default Header