子组件向父组件通信
子组件向父组件通信,用自定义事件,onChange 是自定义事件
import { useState } from "react";
function ToggleButton({ value, onChange }) {
const handleClick = () => {
onChange(!value);
};
return (
<button style={{ width: "60px" }} onClick={handleClick}>
<span>{value ? "On" : "Off"}</span>
</button>
);
}
export default () => {
const [on, setOn] = useState(true);
return (
<>
<h1>Toggle Button</h1>
<ToggleButton value={on} onChange={(value) => setOn(value)} />
</>
);
};