【问题标题】:Passing data to sibling components with react hooks?使用反应钩子将数据传递给兄弟组件?
【发布时间】:2020-09-02 07:08:01
【问题描述】:

我想将变量usernamesibling1 组件传递给sibling2 组件并在那里显示。

Sibling1 组件:

const sibling1 = ({ usernameData }) => {
   // I want to pass the username value I get from input to sibling2 component
  const [username, setUsername] = useState(""); 

  const handleChange = event => {
    setUsername(event.target.value);
  };

  return (
    <Form.Input
        icon='user'
        iconPosition='left'
        label='Username'
        onChange={handleChange}
      />
    <Button content='Login' onClick={handleClick} />
  )
}

export default sibling1;

Sibling2 组件:

export default function sibling2() {
  return (
    <h1> Here is where i want to display it </h1>
  )
}

【问题讨论】:

  • 是从sibling1调用sibling2吗?如果是这样,您可以传递道具。否则您需要存储应用内状态并从那里获取。
  • @QuentinGrisel 我们不知道他是否投反对票;)(顺便说一句,我不是)我怀疑有些回答者有时会在投下不健康的投反对票时进行连续投反对票
  • @giorgim 是的,我后来考虑过了。但该建议仍然有效。我这么说并没有什么不好的意思,这只是徒劳的

标签: javascript reactjs react-hooks


【解决方案1】:

您需要在兄弟姐妹的父母中处理您的用户名。那么您可以将setUsername 传递给您的兄弟姐妹1,并将userName 传递给您的兄弟姐妹2。当sibling1 使用setUsername 时,它​​会更新你的父状态并重新渲染你的sibling2(因为prop 被编辑了)。

它看起来像这样:

const App = () => {
  const [username, setUsername] = useState('Default username');
  return (
    <>
      <Sibling1 setUsername={setUsername} />
      <Sibling2 username={username} />
    </>
  )
}

const Sibling2 = ({username}) => {
  return <h1> Helo {username}</h1>;
}

const Sibling1 = ({setUsername}) => {
  return <button onClick={setUsername}>Set username</button>;
}

【讨论】:

  • 这个!!对我来说这样一个“困难”问题的最佳解释。谢谢:)
  • 不客气 ;) 请记住,基于组件的语言就像树一样,所以如果叶子需要什么东西,大部分时间它都由树干提供;)
【解决方案2】:

最佳方式:React Context + hooks

你可以使用 React 上下文。看看这个例子:

https://codesandbox.io/s/react-context-api-example-0ghhy

【讨论】:

    【解决方案3】:

    在这两个组件的父级中创建一个上下文,您将在其中存储一个值和值设置器(最好来自 useState)。所以,它看起来像这样:

    export const Context = React.createContext({ value: null, setValue: () => {} });
    
    export const ParentComponent = () => {
     const [value, setValue] = useState(null);
    
     return (
      <Context.Provider value={{value, setValue}}>
       <Sibling1 />
       <Sibling2 />
      </Context.Provider>
     );
    

    然后在兄弟姐妹中你像这样使用它:

    const Sibling1 = () => {
     const {setValue} = useContext(Context);
    
     const handleChange = event => {
      setValue(event.target.value);
     };
     // rest of code here
    }
    
    const Sibling2 = () => {
     const {value} = useContext(Context);
    
     return <h1>{value}</h1>;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-10
      • 2018-01-27
      • 2023-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多