使用反应钩子将数据传递给同级组件

使用反应钩子将数据传递给同级组件

本文介绍了使用反应钩子将数据传递给同级组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一个变量用户名"从sibling1 组件传递给sibling2 组件并在那里显示.

I want to pass a variable 'username' from sibling1 component to sibling2 component and display it there.

Sibling1 组件:

Sibling1 component:

´´´

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 组件:

Sibling2 component:

´´´

export default function sibling2 () {

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

´´´

推荐答案

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

You will need to handle your userName in the parent of your siblings. then you can just pass setUsername to your sibling1, and userName to your sibling2. When sibling1 use setUsername, it will update your parent state and re-render your sibling2 (Because the prop is edited).

这是它的样子:

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

这篇关于使用反应钩子将数据传递给同级组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 03:21