使用React钩子将数据传递到同级组件?

时间:2020-05-16 12:08:59

标签: reactjs react-hooks react-component

我想将变量'username'从sibling1组件传递到sibling2组件并在其中显示。

Sibling1组件:

´´´

const sibling1 = ({usernameData}) => {

    const [username, setUsername] = useState("");  // i want to pass the username value i get from input to sibling2 component


    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;

´´´

兄弟姐妹2组件:

´´´

export default function sibling2 () {

  return (
   <h1> Here is where i want to display it </h1>
}

´´´

3 个答案:

答案 0 :(得分:6)

您将需要在兄弟姐妹的父母中处理您的userName。那么您只需将setUsername传递给您的兄弟姐妹1,并将userName传递给您的兄弟姐妹2。当sibling1使用setUsername时,它将更新您的父状态并重新渲染您的sibling2(因为道具已编辑)。

这是什么样子:

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>;
}

答案 1 :(得分: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>;
}

答案 2 :(得分:1)

最佳方法:React Context +钩子

您可以使用React Context。看一下这个例子:

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