是否有一种无缝方法可以在 REACT TS 组件包装器中组合自定义和本机 props?
P粉186897465
P粉186897465 2024-03-30 17:01:40
0
1
346

我有几个组件可以扩展输入、按钮、表格等元素的本机功能,但我发现必须在团队需要时包含每个事件处理程序和道具是很乏味的。

我尝试简单地使组件道具类型扩展本机道具类型,然后使用对象传播自动应用所有本机道具。下一个问题是不支持自定义道具,并且不应将其应用于原生元素。

为了解决这个问题,我找到的唯一解决方案是复制组件参数中每个自定义道具的名称,如下所示:{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

P粉186897465
P粉186897465

全部回复(1)
P粉826283529

您是否尝试过将 interfaceextends 一起使用?

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;
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!