gos*_*d12 7 reactjs react-component react-hooks
我想将一个变量“用户名”从兄弟 1 组件传递给兄弟 2 组件并在那里显示。
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;
Run Code Online (Sandbox Code Playgroud)
'''
Sibling2 组件:
'''
export default function sibling2 () {
return (
<h1> Here is where i want to display it </h1>
}
Run Code Online (Sandbox Code Playgroud)
'''
Que*_*sel 20
您需要在兄弟姐妹的父级中处理您的用户名。然后你可以传递setUsername给你的兄弟姐妹1和userName你的兄弟姐妹2。当兄弟 1 使用 setUsername 时,它会更新你的父状态并重新渲染你的兄弟 2(因为道具被编辑)。
这是它的样子:
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>;
}
Run Code Online (Sandbox Code Playgroud)
小智 5
在这两个组件的父组件中创建一个上下文,您将在其中存储值和值设置器(最好来自 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>
);
Run Code Online (Sandbox Code Playgroud)
然后在兄弟姐妹中,您可以像这样使用它:
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>;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9277 次 |
| 最近记录: |