【问题标题】:spread props in react using typescript使用打字稿在反应中传播道具
【发布时间】:2020-08-21 09:11:42
【问题描述】:

当我第一次开始在 react 中调整 typescript 时,我注意到我不能使用 ...props,因为 typescript 会检查组件中传递的每一个 prop。这很棒,但也很烦人,我必须以声明方式将本地道具(如 id、name 等)作为道具传递。


interface MyComponentProps {
  name: string,
  id: string,
  placeholder: string
}

const MyComponent = ({
  name,
  id,
  placeholder
}: MyComponentProps) => {
  return <input type="text" placeholder={placeholder} name={name} id={id}/>
}
export default function App() {
  return (
    <div className="App">
      <MyComponent placeholder="Name" name="something" id="myInput" />
    </div>
  );
}

【问题讨论】:

    标签: javascript reactjs typescript


    【解决方案1】:

    您应该编辑您的界面,使其扩展 HTML input 元素的属性:

    interface MyComponentProps extends InputHTMLAttributes< HTMLInputElement>)  {
      // add other custom props
    }
    
    const MyComponent: React.FC<MyComponentProps> = (props) => (...)
    

    【讨论】:

    • 除了 InputHTMLAttributes 还有什么其他类型?对于divli 等,我怎么知道这些?
    • 你可以参考这个备忘单! saltycrane.com/cheat-sheets/typescript/react/latest一旦掌握了它就不会那么复杂了
    • 这对我很有帮助,我很生气你被否决了。对于未来的读者,我需要这个作为锚“a”链接,我使用LinkHTMLAttributes 而不是InputHTMLAttributes。在我的编辑器中,我只是导航到定义类型的文件,并且它们都具有受支持的属性。
    【解决方案2】:

    您可以将其显式转换为HTMLAttributes

    声明一个接口,比如组件的 props 与 HTMLAttributes 的联合

    interface MyComponentProps = {}
    
    const MyComponent: React.FC<MyComponentProps & HTMLAttributes>...
    

    你可以在这里找到详细的解释: https://stackoverflow.com/a/40032869/4186110

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-22
      • 2021-09-12
      • 2018-10-26
      • 2020-05-13
      • 2018-09-19
      • 1970-01-01
      • 1970-01-01
      • 2021-05-24
      相关资源
      最近更新 更多