简体   繁体   English

typescript 传播运算符用于反应中的道具抛出错误

[英]typescript spread operator for props in react throw error

When using typescript with react, I want to skip passing every single props especially native props for HTML like id, name, placeholder etc but I got error on my {...props}将 typescript 与 react 一起使用时,我想跳过每个道具,尤其是 HTML 的原生道具,例如 id、名称、占位符等,但我的{...props}出现错误

I've extended my interface with InputHTMLAttributes so that typescript didn't check my props but it still got unresolved error我已经使用InputHTMLAttributes扩展了我的界面,因此 typescript 没有检查我的道具,但仍然出现未解决的错误

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 https://codesandbox.io/s/elegant-forest-42t4b?file=/App.tsx

First of all, you need to use rest spread syntax to get props and not destructure like an object首先,您需要使用 rest 扩展语法来获取道具,而不是像 object 那样进行解构

Secondly interface needn't define props as an object其次接口不需要将 props 定义为 object

Lastly you have {..props} instead of {...props} .最后你有{..props}而不是{...props} Notice 3 dots before 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 工作演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM