【问题标题】:typescript spread operator for props in react throw error用于反应抛出错误中的道具的打字稿传播运算符
【发布时间】:2020-05-07 07:03:20
【问题描述】:

当使用带有 react 的 typescript 时,我想跳过每个道具,尤其是 HTML 的原生道具,例如 id、名称、占位符等,但我的 {...props} 出现错误

我已经用InputHTMLAttributes 扩展了我的界面,所以打字稿没有检查我的道具,但它仍然得到未解决的错误

import React, { InputHTMLAttributes } from "react";
import "./styles.css";

interface MyComponentProps extends InputHTMLAttributes<HTMLInputElement> {
  nonNativeProp: string;
  props: object
}

const MyComponent: React.FC<MyComponentProps> = ({
  nonNativeProp,
  props
}) => {
  return <input type="text" {..props} />;
};

export default function App() {
  return (
    <div className="App">
      <MyComponent
        nonNativeProp="abc"
        placeholder="Name"
        name="something"
        id="myInput"
        data-custom="custom-attr"
      />
    </div>
  );
}

https://codesandbox.io/s/elegant-forest-42t4b?file=/App.tsx

【问题讨论】:

  • 可能是台风……在展开运算符中应该有 3 个点而不是 2 个点

标签: javascript reactjs typescript


【解决方案1】:

首先,你需要使用rest spread语法来获取props,而不是像对象那样解构

其次,界面不需要将 props 定义为对象

最后你有{..props} 而不是{...props}。注意 props 前的 3 个点

interface MyComponentProps extends InputHTMLAttributes<HTMLInputElement> {
  nonNativeProp: string;
}

const MyComponent: React.FC<MyComponentProps> = ({
  nonNativeProp,
  ...props
}) => {
  return <input type="text" {...props} />;
};

export default function App() {
  return (
    <div className="App">
      <MyComponent
        nonNativeProp="abc"
        placeholder="Name"
        name="something"
        id="myInput"
        data-custom="custom-attr"
      />
    </div>
  );
}

Working demo

【讨论】:

  • 你说接口需要将prop定义为对象,但是当你把它留空时我没有看到任何警告?
  • 对不起,这是我的错字,完全改变了意思。我的意思是接口不需要将道具定义为对象。更新了帖子
猜你喜欢
  • 2018-12-30
  • 1970-01-01
  • 1970-01-01
  • 2020-08-21
  • 2021-03-15
  • 2016-03-14
  • 2021-09-12
相关资源
最近更新 更多