繁体   English   中英

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

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

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

我已经使用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

首先,您需要使用 rest 扩展语法来获取道具,而不是像 object 那样进行解构

其次接口不需要将 props 定义为 object

最后你有{..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>
  );
}

工作演示

暂无
暂无

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

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