Max*_*hke 8 javascript typescript reactjs
我有一个小的 React 组件,其中子组件是一个函数。我似乎不知道如何children在 TypeScript 中定义 prop。
class ClickOutside extends React.PureComponent<Props, {}> {
render() {
const { children } = this.props;
return children({ setElementRef: this.setElementRef });
}
}
Run Code Online (Sandbox Code Playgroud)
我这样称呼它:
<ClickOutside onOutsideClick={() => this.setState({ isOpen: false })}>
{({ setElementRef }) => (
<div ref={setElementRef}>
{trigger}
{children}
</div>
)}
</ClickOutside>
Run Code Online (Sandbox Code Playgroud)
这就是我试图定义的道具,但它根本不起作用。我尝试过其他几件事但都失败了,我有点迷失在这里。
type Props = {
children: ({ setElementRef: (el: HTMLElement) => any }) => React.ReactNode,
onOutsideClick: Function,
}
Run Code Online (Sandbox Code Playgroud)
编辑:
这产生';' expected.于=>
当我这样更改类型定义时:
type Props = {
children: ({ setElementRef: (el: HTMLElement) => any }),
onOutsideClick: Function,
}
Run Code Online (Sandbox Code Playgroud)
它会产生以下错误:
无法调用类型缺少调用签名的表达式。类型 '{ setElementRef: (el: HTMLElement) => any; } | ({ setElementRef: (el: HTMLElement) => any; } & string) | ({ setElementRef: (el: HTMLElement) => any; } & string) | ({ setElementRef: (el: HTMLElement) => 任意; } & number) | ({ setElementRef: (el: HTMLElement) => 任何; } & false) | ({ ...; } & true) | ({ ...; } & ReactElement<...>) | ({ ...; } & ReactNodeArray) | ({ ...; } & ReactNodeArray) | ({ ...; } & Re...' 没有兼容的调用签名。
setElementRef您需要在 prop的解构对象参数中定义 的类型children:
type Props = {
children(options: { setElementRef(el: HTMLElement): any } ): React.ReactNode;
};
Run Code Online (Sandbox Code Playgroud)
请记住,在解构对象时,:符号会执行其 JavaScript 职责并重新分配属性名称,而在此示例中,您希望它指定类型。
| 归档时间: |
|
| 查看次数: |
7168 次 |
| 最近记录: |