reactjs - 使用组件外功能组件的回调定义
问题描述
我得到了一个内部带有回调的 React 功能组件。我想在 Component 外部定义一个结构,其中包含一个包含对回调的引用的字段,但不仅仅是它获得的第一个定义,而且它应该在每次最新呈现该回调时都保存以避免关闭问题。
我的意思的伪代码:
let someStruct = {
field: MyComponent.callback
}
const MyComponent = props => {
const callback = () => { ...some code that depends on the state of MyComponent }
}
我该怎么做?再次考虑关闭,我需要最新的回调以及它使用的正确数据。
解决方案
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
},
}
推荐阅读
- javascript - 过滤javascript异步获取响应
- javascript - SCSS 的 Flexbox 在 Firefox 上正常工作,但在其他浏览器(例如 Chrome、Edge 等)上不能正常工作
- c# - Chrome 未设置会话的 Cookie
- javascript - keep getting empty result on my previous promise
- angular - 如何防止 Angular 工作区中的跨项目?
- ruby-on-rails - Poro 的 FactoryBot 工厂导致未定义的方法“构建”
- python - 导入自己的包和模块的问题
- list - 使用的最佳数据结构
- python - 根据列表中列的值过滤熊猫数据框列
- python - 使用 SSH 的 Python MySQL 连接