 
                        我有几个组件可以扩展输入、按钮、表格等元素的本机功能,但我发现必须在团队需要时包含每个事件处理程序和道具是很乏味的。
我尝试简单地使组件道具类型扩展本机道具类型,然后使用对象传播自动应用所有本机道具。下一个问题是不支持自定义道具,并且不应将其应用于原生元素。
为了解决这个问题,我找到的唯一解决方案是复制组件参数中每个自定义道具的名称,如下所示:{customProp1,customProp2,...nativeProps}。然而,这个解决方案虽然比必须添加所有原生道具要好得多,但它迫使我复制所有道具,并且我失去了道具。我喜欢用来区分 props 和局部变量的前缀。
有没有一种巧妙的方法可以从自定义道具中过滤掉原生道具?
我想要实现的目标的示例:
import React from 'react'
type Props = {
    color: string,
}
const Button = ({...props}: Props, {...nativeProps} : React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>) => {
  return (
    <button {...nativeProps} style={{backgroundColor: props.color}}  />
  )
}
export default Button
我目前的最佳解决方案包括复制每个道具名称并对其余道具使用扩展运算符。
import React from 'react'
type CustomProps = {
    color: string,
    label: React.ReactNode,
    name: string,
}
type Props = CustomProps & Omit<React.DetailedHTMLProps<React.ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>, keyof CustomProps>;
const Button = ({color, label, ...props}: Props) => {
  return (
    <>
        {label}
        <button {...props} style={{backgroundColor: color}} />
    </>
  )
}
export default Button
            Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
您是否尝试过将
interface与extends一起使用?import React from 'react'; interface IButtonProps extends React.DetailedHTMLProps, HTMLButtonElement > { color: string; } const Button = ({ color, ...props }: IButtonProps) => { return ; }; export default Button;否则,您可以嵌套本机按钮道具:
import React from "react"; interface IButtonProps { color: string; buttonProps?: React.DetailedHTMLProps, HTMLButtonElement >; } const Button = ({ buttonProps, ...props }: IButtonProps) => { return ; }; const App = () => { return ; }; export default App;