【问题标题】:React typescript pass props not declared in the interface?React typescript pass props 未在界面中声明?
【发布时间】:2021-08-08 21:23:28
【问题描述】:

您好,我刚刚开始使用 typescript 并做出反应!

我有这个简单的按钮组件

import React from 'react'
interface Props{
    className?:string,
    onClick:()=> void,
    children: React.ReactNode
}
export const Button:React.FC<Props> = ({onClick = ()=>1,children,className = "",...rest}) =>{
return(
        <button onClick={onClick} className={"r-button cursor-p br " + className} {...rest}>
            {children}
        </button>)
} 

它工作得很好,但是如果我尝试向组件添加一个我只用于样式的属性,就像这样

<Button loading="true" onClick={()=>console.log("yoohoi")}>Click me!</Button>

我在加载属性中收到此错误

Type '{ children: (Element | ReactNode)[]; className: string; onClick: () => Promise<void>; loading: string; }' is not assignable to type 'IntrinsicAttributes & Props & { children?: ReactNode; }'.
  Property 'loading' does not exist on type 'IntrinsicAttributes & Props & { children?: ReactNode; }'.

所以我的问题是如何处理仅用于样式目的的传递属性而不必在道具界面中声明它们?我认为 ...rest 会完成这项工作:/

【问题讨论】:

  • 您可以为此使用 data-* 属性。但是,为什么不只使用自定义类,例如 classNanme='loading'
  • :O好像很喜欢,为什么数据加载有效?
  • 因为数据属性正是为此目的而设计的,幸运的是 React 尊重这一点),请参阅答案

标签: reactjs typescript


【解决方案1】:

你可以使用

  • 任一 data-* 属性(因为 data 属性被设计为自定义属性和React allows them

  • 或者传递className,它会在加载时设置元素样式

【讨论】:

  • 哦,我明白了!感谢您的解释,我可以肯定地使用一个类,但我想看看如何允许使用属性,因为这个组件可能被其他可以使用属性来设置样式的人使用,而不仅仅是类:)
  • 当然!我很快就会接受答案(由于某种原因必须等待 4 分钟)
猜你喜欢
  • 1970-01-01
  • 2018-11-26
  • 2020-10-24
  • 2021-12-31
  • 2018-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多