简体   繁体   中英

I want to access parent useState in child component

import React, { useState } from "react";

const Sidebar = ({ sidebarActive, setSidebarActive }) => {

 return (
    <>
      {/* Hamburger button */}
      <button
        className={
          sidebarActive
            ? "hamburgerButton sidebar-oepn"
            : "hamburgerButton sidebar-closed"
        }
        type="button"
        onClick={() => setSidebarActive(!sidebarActive)}
      >
        <i className="fa fa-fw fa-bars" />
      </button>
   </>
  );
};

export default Sidebar;

when i run i encounter with following error

Compiled with problems:

ERROR


src\components\VerticalLayout\Sidebar.js
  Line 6:20:  'sidebarActive' is missing in props validation     react/prop-types
  Line 6:35:  'setSidebarActive' is missing in props validation  react/prop-types

Search for the keywords to learn more about each error.

if i do the following, i do not encounter with any error but i also didn't get access to parents useState value

const Sidebar = (props, { sidebarActive, setSidebarActive }) => {

Your first implementation is correct but it showed errors because of this prop types validation .

According to those errors, your component is lackingPropTypes . You need to set it like below

import React, { useState } from "react";
import PropTypes from 'prop-types';

const Sidebar = ({ sidebarActive, setSidebarActive }) => {

 return (
    <>
      {/* Hamburger button */}
      <button
        className={
          sidebarActive
            ? "hamburgerButton sidebar-oepn"
            : "hamburgerButton sidebar-closed"
        }
        type="button"
        onClick={() => setSidebarActive(!sidebarActive)}
      >
        <i className="fa fa-fw fa-bars" />
      </button>
   </>
  );
};

//set prop types
Sidebar.propTypes = {
   sidebarActive: PropTypes.bool,
   setSidebarActive: PropTypes.func
}

export default Sidebar;

You just need to validate the props with propTypes:

Here is a working snippet

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM