我知道使用 ref 可以从父组件调用子组件中的函数。但我的问题是我有多个子组件实例,我需要在所有子组件中调用相同的函数。
// Get a hook function
const {useState, useRef, useImperativeHandle, useEffect} = React;
const Parent = ({title}) => {
const childRef1 = useRef();
const childRef2 = useRef();
const childRef3 = useRef();
const childRef4 = useRef();
const childRef5 = useRef();
const handleClick = () => {
childRef1.current.increment()
childRef2.current.increment()
childRef3.current.increment()
childRef4.current.increment()
childRef5.current.increment()
}
return (
<div>
<p>{title}</p>
<Child num={1} childRef={childRef1} />
<Child num={2} childRef={childRef2} />
<Child num={3} childRef={childRef3} />
<Child num={4} childRef={childRef4} />
<Child num={5} childRef={childRef5} />
<button onClick={() => handleClick()}>
Click me
</button>
</div>
);
};
const Child = ({num, childRef}) => {
const [count, setCount] = useState(0)
useImperativeHandle(childRef, () => ({
increment() {
// if(textEditable)
setCount(count+1)
},
}));
useEffect(() => {
setCount(num)
}, [num])
return (
<div>
{
count
}
</div>
)
}
// Render it
ReactDOM.render(
<Parent title="Example using Hooks:" />,
document.getElementById("react")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>
我的问题是,如果我在地图函数中渲染子组件,我应该怎么做?