【发布时间】:2021-11-29 14:45:30
【问题描述】:
我有两个组件,一个父组件和一个子组件。此子组件位于父组件内。在子组件内部,有一个标签,当它被点击时,一个值被存储在一个单独的状态中,现在当一个父组件内的按钮被点击时,应该打印存储在子组件状态中的值到控制台。
下面有什么
// import Checboxtest from "./Checkboxtest";
import "./styles.css";
const Child = ({ showresult, click }) => {
const [clickedvalue, setClickedValue] = useState("");
const ItemClicked = (e) => {
setClickedValue("Yes");
console.log(clickedvalue);
};
return (
<div className="App">
<h1>Checkbox Value </h1>
<span onClick={ItemClicked}>
<input type="checkbox" /> clik me
</span>
</div>
);
};
export default function Parent() {
const [clickedvalue, setClickedValue] = useState("");
return (
<div className="App">
<h1>
When clicked on the button below, the value of the checkbox inside the
child component should be display on the console.
</h1>
<button
onCick={() => {
console.log(clickedvalue);
}}
>
See checkbox value
</button>
<Child clickedvalue={clickedvalue} setClickedValue={setClickedValue} />
</div>
);
}
【问题讨论】:
-
您已经描述了预期的行为,但您遇到了什么问题?
-
是的,所有的人都写了来完成它没有工作
-
但具体是哪一部分不起作用?
-
欢迎来到 SO!我在其他地方有一个答案可能会有所帮助,How to set one component's state from another component in React,干杯!
标签: javascript reactjs