问题
I got a React functional Component with a callback inside. I want to define a struct outside the Component with a field which holds a reference to the callback, but not just the first definition it got, but it should hold every time the latest rendering of that callback to avoid closure issues.
psuedo code of what I mean:
let someStruct = {
field: MyComponent.callback
}
const MyComponent = props => {
const callback = () => { ...some code that depends on the state of MyComponent }
}
How can I do it? And again considering closure, I need the latest callback with the correct data it uses.
回答1:
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);
Now you can use it outside of this component like this
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>
</>
)
}
If you want to call this callback outside the react components here is a solution I used and it worked (even in production)
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
},
}
来源:https://stackoverflow.com/questions/65603273/use-callback-definition-of-a-functional-component-outside-the-component