我想将变量'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>
}
´´´
您将需要在兄弟姐妹的父母中处理您的userName。那么您只需将setUsername
传递给您的兄弟姐妹1,然后将userName
传递给您的兄弟姐妹2。当兄弟姐妹1使用setUsername时,它将更新您的父状态并重新渲染兄弟姐妹2,因为道具已被编辑。
在反应中,这称为提升状态。一个例子:
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>
)
}
最佳方式:React Context
您可以使用React Context。看一下这个例子: