const MyComponent = (props, ref) => {
const [state, setState] = React.useState(initialState)
const getHandlerFunctions = () => ({
callback: yourDefinedCallBackFunction(state, ...args)
})
React.useImperativeHandle(ref, getHandlerFunctions, [dependencies]);
return <div data-type="your-presentation-component" />
}
export default React.forwardRef(MyComponent);
现在你可以像这样在这个组件之外使用它
const OtherComponent = () => {
const myComponentRef = React.useRef();
const callback = () => {
const { current: mcHandlers } = myComponentRef;
if (!mcHandlers) return
mcHandlers.callback()
}
return (
<>
<MyComponent ref={myComponentRef} />
<button onClick={callback}>execute Callback</button>
</>
)
}
如果您想在react组件之外调用此回调,这是我使用的解决方案并且它有效(即使在生产中)
let _callback = () => {}
const MyComponent = () => {
const [state, setState] = React.useState(initialState)
// you can change dependensis by your need
React.useEffect(() => {
_callback = (...args) => {
console.log('do anything with', state, ...args)
}
return () => {
_callback = () => {}
}
})
}
export const struct = {
get callback() {
return _callback
},
}