【发布时间】:2019-10-15 11:13:45
【问题描述】:
我创建了一个简单的 HOC,它使用自定义挂钩来跟踪鼠标位置。我在 HOC 函数中使用了钩子,我想通过它将该值传递给被包装的组件。
没关系,我将函数作为道具传递,我可以使用this.props 控制台记录该道具。正如预期的那样,我在控制台中得到了输出{position: {…}}。当我展开该日志对象时,我可以看到输出 position: {x: 479, y: 396},这正是我想要的。
但是,当我想使用this.props.position 访问实际对象时,它只会给我一个错误:
TypeScript error in /Users/dvidovic/Projects/hooks-in-classes/src/components/HooksHOC.tsx(6,28):
Property 'position' does not exist on type 'Readonly<{}> & Readonly<{ children?: ReactNode; }>'. TS2339
这是 HOC:
import React from 'react';
import { useMousePosition } from '../hooks/useMousePosition';
export const withHooksHOC = (Component: any) => {
return (props: any) => {
return <Component position={useMousePosition()} {...props} />;
};
};
这是包装好的组件:
import React from 'react';
import { withHooksHOC } from './withHooksHOC';
class HooksHOC extends React.Component {
render() {
console.log(this.props); // this works
console.log(this.props.position); // this throws an error
return (
<div style={{ marginTop: '100px', fontSize: '72px' }}>Some text</div>
);
}
}
export default withHooksHOC(HooksHOC);
我必须改变什么才能访问位置对象?
【问题讨论】:
-
使用
this.props['position']有效吗? -
嗯,也许是因为你在将它作为道具传递时调用了该函数?我假设它返回鼠标位置对象。也许试试
position={useMousePosition()}然后console.log(this.props.position());
标签: reactjs higher-order-components