将数据传递给具有React钩子的同级组件?

问题描述 投票:0回答:3

我想将变量'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;

´´´

Sibling2组件:

´´´

export default function sibling2 () {

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

´´´

reactjs react-hooks react-component
3个回答
0
投票

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


0
投票

在反应中,这称为提升状态。一个例子:

const Parent = () => {

    // username now actually lives in the parent
    // Hence no need to keep it in state of Sibling1 anymore
    const [username, setUsername] = useState(""); 

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



    return (
        <div>
          <Sibling1 username={username} onChange={handleChange}/>
          <Sibling2 username={username}/>
      </div>
    )
}

-1
投票

最佳方式:React Context

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

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

© www.soinside.com 2019 - 2024. All rights reserved.