将属性作为变量传递给组件

时间:2021-05-15 10:56:43

标签: javascript reactjs

我有如下父组件:

import React from "react"
import PropTypes from "prop-types"
import Header from "./header"
import "./layout.css"
import TopBar from "./topbar"
import Bottom from "./bottom"

const Layout = ({ children, isMobile = false }) => {
  const mainStyle = !isMobile ? ".main-desktop" : ".main-mobile"
  //children.isMobile = isMobile

  return (
    <>
      <Header siteTitle={'MAIN TITLE'}
        moto={'SLOGAN.'}
        isMobile={isMobile} />
      <TopBar isMobile={isMobile} />
      <div
        style={{
          margin: `0 auto 0 auto`,
          minHeight: `50%`,
          padding: `0 1.0875rem 1.45rem`,
          paddingLeft: "90px"
        }}
      >
        <main className={mainStyle}>{children}</main>
        <br />
        <br />
      </div>
      <Bottom isMobile={isMobile} />
    </>
  )
}

Layout.propTypes = {
  children: PropTypes.node.isRequired,
}

export default Layout

我有一个子组件如下:

从“反应”导入反应 从“../components/seo”导入SEO

const ContactUsPage = ({ isMobile = false }) => (
    <>
        <SEO title="Contact Us"
    </>
)

export default ContactUsPage

ContactUsPage 被 Gatsby 框架在 Layout 内部调用到 children 变量中。现在,我想从 isMobile 传递 Layout 属性。我尝试直接设置它,但给出了对象不可扩展的错误。 有什么方法,如果可能,为可变组件设置属性的正确方法是什么?

2 个答案:

答案 0 :(得分:0)

在父组件中作为回报:

<ContactUsPage isMobile={isMobile} />

ContactUsPage 组件内部:

const ContactUsPage = ({ isMobile }) => {
  return (
    <div>
    </div>
  );
};

答案 1 :(得分:0)

我认为你可以通过两种方式做到这一点,Gatsby 方式和 React Context 方式:

盖茨比之道:

Gatsby 允许您将 state 属性传递给其 <Link/> 组件。 然后可以从页面组件(自动接收 location 属性。请参阅 Gatsby documentation

上下文方式:

创建一个包含 isMobile 值和组件提供程序的 React 上下文:

export const MobileContext = React.createContext({ isMobile: false });

export MobileProvider = ({ children }) => {
  const [isMobile, setIsMobile] = useState(false);

  // Define your logic to check if it is mobile or not

  const value = useMemo(() => ({ isMobile }), [isMobile]);

  return (
    <MobileContext.Provider value={value}>
      {children}
    </MobileContext.Provider>
  )
}

然后用它包裹你的布局。

然后您可以使用 const { isMobile } = useContext(MobileContext); 访问所有布局子项(及其子项)的上下文值。 检查 React context documentation