【问题标题】:Send state/props to another component in React with onClick使用 onClick 将 state/props 发送到 React 中的另一个组件
【发布时间】:2021-01-12 00:24:40
【问题描述】:

我有两个独立的组件,它们没有简单的父子关系。

ComponentFolderA 
|
ButtonComponent 

ComponentFolderB
|
BannerComponent

我想在用户单击按钮时发送setState 并将该值发送到BannerComponent

解决这个问题的最佳方法是什么?

【问题讨论】:

    标签: reactjs onclick react-props setstate buttonclick


    【解决方案1】:

    在功能组件中,您可以在父组件中为 ButtonComponent 和 BannerComponent 创建状态。然后按照下面的例子,

    const Parent = () => {
        const [sampleState, setSampleState] = useState(null);
    
        return (
          <>
              <BannerComponent sampleState={sampleState} />
              <ButtonComponent setSampleState={setSampleState} />
          </>
        )
    }
    

    然后您可以将 setSampleState 作为 ButtonComponent 中的道具访问。

    另外,请查看Best practice way to set state from one component to another in React,您可以使用状态管理器(Context APIRedux

    【讨论】:

      【解决方案2】:

      将状态保留在父级中,并将状态设置功能向下发送到您的 Button。

      const Parent = () => {
        const [myState, setMyState] = useState(false);
        
        return (
          <>
            <BannerComponent myState={myState} />
            <ComponentWithButton setMyState={setMyState} />
          </>
        )
      }
      
      const ComponentWithButton = props => {
        return (
          <Button onClick={() => props.setMyState(true)} />
        )
      }
      

      【讨论】:

        猜你喜欢
        • 2023-03-04
        • 2021-09-29
        • 2014-11-05
        • 1970-01-01
        • 2019-06-23
        • 1970-01-01
        • 1970-01-01
        • 2020-12-18
        • 1970-01-01
        相关资源
        最近更新 更多