Use callback definition of a functional component outside the component

狂风中的少年 提交于 2021-02-10 18:23:44

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!