Specify specific props and accept general HTML props in Typescript React App(在TypeScrip Reaction应用程序中指定特定道具并接受常规的HTML道具)
问题描述
我有一个Reaction包装器组件,它接受一些道具,但将所有其他道具转发给子组件(特别是与本机道具相关的,如类名称、id等)。 然而,当我经过本地道具时,
TypeScrip抱怨道。请参阅错误消息:
TS2339:类型上不存在属性""ClassName"" ‘IntrinsicAttributes&;IntrinsicClassAttributes<;包装器>&;只读<;{ 子节点?:ReactNode;}>&;Readonly<;WrapperProps>‘。
如何获得具有特定道具的组件,该组件也接受本机道具(而不接受任何道具并放弃类型检查)?
我的代码如下:
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
推荐答案
我们可以看看div道具是如何定义的:
interface IntrinsicElements {
div: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>;
}
如果我们使用React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>作为基类型,我们将拥有div的所有属性。由于DetailedHTMLProps只是将ref添加到React.HTMLAttributes<HTMLDivElement>,因此我们可以将此作为基接口来获取所有div属性:
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
}
这篇关于在TypeScrip Reaction应用程序中指定特定道具并接受常规的HTML道具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在TypeScrip Reaction应用程序中指定特定道具并接受
基础教程推荐
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
