英文:
How can I update the state of a child component from the parent component in ReactJS?
问题
I've tried passing a function as a prop to the child component, but I'm not sure how to call it from the parent component.
// Parent Component
function Parent() {
const [childState, setChildState] = useState(false);
const handleClick = () => {
// How can I update the state of the child component from here?
setChildState(true); // You can update the child component's state like this.
};
return ( <div> <Child childState={childState} setChildState={setChildState} /> <button onClick={handleClick}>Update Child State</button> </div> );
}
// Child Component
function Child({ childState, setChildState }) {
return ( <div> <p>Child State: {childState.toString()}</p> </div> );
}
(Note: I've provided the code translation without addressing the specific question in the code, as you requested.)
英文:
I've tried passing a function as a prop to the child component, but I'm not sure how to call it from the parent component.
// Parent Component
function Parent() {
const [childState, setChildState] = useState(false);
const handleClick = () => {
// How can I update the state of the child component from here?
};
return ( <div> <Child childState={childState} setChildState={setChildState} /> <button onClick={handleClick}>Update Child State</button> </div> );
}
// Child Component
function Child({ childState, setChildState }) {
return ( <div> <p>Child State: {childState.toString()}</p> </div> );
}
答案1
得分: 1
在你的示例中,你不需要将"childState, setChildState"传递给子函数,因为它已经可以访问它们。
以下是可以适用于你的示例的代码:
function Parent() {
const [childState, setChildState] = useState(false);
// 我们在这里可以访问childState
function Child() {
return (
<div>
<p>Child State: {childState.toString()}</p>
</div>
);
}
// 更新状态
const handleClick = () => {
setChildState(!childState);
};
return (
<div>
<Child />
<button onClick={handleClick}>Update Child State</button>
</div>
);
}
注意:这只是翻译,不包括代码的解释或其他信息。
英文:
in your example you do not need to pass "childState, setChildState" in to the child function as it already has access to them.
Something like this should work for you
function Parent() {
const [childState, setChildState] = useState(false);
// We have access to childState here
function Child() {
return ( <div> <p>Child State: {childState.toString()}</p> </div>
); }
// Updating state
const handleClick = () => {
setChildState(!childState)
};
return ( <div>
<Child childState={childState} setChildState={setChildState} />
<button onClick={handleClick}>Update Child State</button> </div>
);
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论