【问题标题】:React change state of one component from another反应一个组件从另一个组件的更改状态
【发布时间】:2021-06-30 00:44:13
【问题描述】:

我需要从另一个组件更改侧边栏组件的状态。

我的代码:

Sidebar.tsx >

const SideBar: React.FC = () => {

    const [open, setOpen] = useState<boolean>(false);

    function switchSidebar() {
       setOpen(!open);
    }

    const bar = useMemo(() => <Menu open={open} sidebar={true} />, [open])

        return (
           <>
              <SidebarButton /> 
              { bar }
           </>

} 

SidebarButton.tsx >

export const SidebarButton:React.FC = () => {
  return(
        <svg xmlns="http://www.w3.org/2000/svg" onMouseDown={/* ? */}>
            <path stroke="currentColor" strokeWidth={3} d="M0 1.5h28M0 10.5h28M8 19.5h20"/>
        </svg>
 )
}

菜单.tsx >

const Menu: React.FC = ({sidebar, open, data = HeaderData}) => {
       return (
         <ul>
            <SidebarButton /> 
            { /* Other things to render */ }
         </ul>
       )
}

您如何看到我需要一种方法来从 SidebarButton 更改 Sidebar 中包含的状态。

【问题讨论】:

    标签: reactjs next.js


    【解决方案1】:

    您可以将 setOpen 函数作为道具传递给 SidebarButton 组件,然后只需调用 setOpen 函数来更改值。

    <SidebarButton setOpen={setOpen} />
    

    如果您还想从菜单组件中调用它,那么您可能需要将 open 的声明移动到侧边栏和菜单之间通用的更高组件,因为道具只能向下传递。

    【讨论】:

      猜你喜欢
      • 2020-10-12
      • 1970-01-01
      • 2021-10-18
      • 1970-01-01
      • 2020-07-01
      • 2020-11-25
      • 1970-01-01
      • 1970-01-01
      • 2019-10-18
      相关资源
      最近更新 更多