首页 > 解决方案 > 使用组件外功能组件的回调定义

问题描述

我得到了一个内部带有回调的 React 功能组件。我想在 Component 外部定义一个结构,其中包含一个包含对回调的引用的字段,但不仅仅是它获得的第一个定义,而且它应该在每次最新呈现该回调时都保存以避免关闭问题。

我的意思的伪代码:

let someStruct = {
  field: MyComponent.callback
}

const MyComponent = props => {
  const callback = () => { ...some code that depends on the state of MyComponent }
}

我该怎么做?再次考虑关闭,我需要最新的回调以及它使用的正确数据。

标签: reactjs

解决方案



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>
    </>
  )
}

如果您想在反应组件之外调用此回调,这是我使用的一个解决方案并且它有效(即使在生产中)

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
  },
}

推荐阅读