import React, { useState, useRef, useEffect } from "react";
const Child = (props) => {
const [count, setCount] = useState(0);
// 暴露方法
useEffect(() => {
if (props.bindRef) {
props.bindRef({
increment: () => setCount((c) => c + 1),
reset: () => setCount(0),
getValue: () => count,
});
}
}, [props.bindRef, count]);
return (
<div style={{ border: "1px solid #ccc", padding: 16 }}>
<p>子组件计数: {count}</p>
<button onClick={() => setCount(count + 1)}>子组件 +1</button>
</div>
);
};
const Parent = () => {
const childApi = useRef(null);
const handleReset = () => {
childApi.current?.reset();
};
const handleIncrement = () => {
childApi.current?.increment();
};
const handleGetValue = () => {
alert(`当前子组件 count 值为:${childApi.current?.getValue()}`);
};
return (
<div style={{ padding: 20 }}>
<h2>父组件</h2>
<div style={{ marginBottom: 10 }}>
<button onClick={handleIncrement}>父组件调用 +1</button>{" "}
<button onClick={handleReset}>父组件调用 reset()</button>{" "}
<button onClick={handleGetValue}>获取子组件值</button>
</div>
<Child bindRef={(api) => (childApi.current = api)} />
</div>
);
};
export default Parent;