在 Typescript React App 中指定特定的道具并接受一般的 HTML 道具

新手上路,请多包涵

我有一个 React Wrapper 组件,它接受一些道具,但将所有其他道具转发给子组件(尤其是与 className、id 等本机道具相关的)。

但是,当我传递本机道具时,Typescript 会抱怨。查看错误信息:

TS2339:类型“IntrinsicAttributes & IntrinsicClassAttributes< Wrapper > & Readonly< { children?: ReactNode; 上不存在属性“className” }> & Readonly‘。

我怎样才能得到一个具有特定道具的组件,它也接受原生道具( 接受任何道具并放弃类型检查)?

我的代码如下所示:

 interface WrapperProps extends JSX.IntrinsicAttributes {
  callback?: Function
}

export class Wrapper extends React.Component<WrapperProps>{
  render() {
    const { callback, children, ...rest } = this.props;
    return <div {...rest}>
      {children}
    </div>;
  }
}

export const Test = () => {
  return <Wrapper className="test">Hi there</Wrapper>
}

仅供参考:我在这里发现了一个类似的问题,但答案基本上放弃了类型检查,我想避免这种情况: Link to SO-Question

原文由 Sergej Herbert 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 341
2 个回答

我们可以看看 div props 是如何定义的:

 interface IntrinsicElements {
    div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>;
}

如果我们使用 React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement> 作为基本类型,我们将拥有 div 的所有属性。 Since DetailedHTMLProps just adds ref to React.HTMLAttributes<HTMLDivElement> we can use just this as the base interface to get all div properties:

 interface WrapperProps extends React.HTMLAttributes<HTMLDivElement> {
  callback?: Function
}

export class Wrapper extends React.Component<WrapperProps>{
  render() {
    const { callback, children, ...rest } = this.props;
    return <div {...rest}>
      {children}
    </div>;
  }
}

export const Test = () => {
  return <Wrapper className="test">Hi there</Wrapper> // works now
}

原文由 Titian Cernicova-Dragomir 发布,翻译遵循 CC BY-SA 4.0 许可协议

JSX.IntrinsicElements 有这个信息,例如

const FooButton: React.FC<JSX.IntrinsicElements['button']> = props => (
  <button {...props} className={`foo ${props.className}`} />
)

// alternative...
const FooButton: React.FC<React.PropsWithoutRef<
  JSX.IntrinsicElements['button']
>> = props => <button {...props} className={`foo ${props.className}`} />

react-typescript-cheatsheet 项目中发现了这一点。

原文由 schpet 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题