Javascript 允许对带有Typescript的React组件使用任意数据-*属性

Javascript 允许对带有Typescript的React组件使用任意数据-*属性,javascript,reactjs,typescript,Javascript,Reactjs,Typescript,是否有一种方法允许下面的React组件上的动态数据-*属性与Typescript一起使用?我希望能够: 支持类名,样式,以及其他常见的HTML属性 允许数据-*属性 允许自定义组件道具,如custom 接口ITestProps{ 自定义?:字符串; } 导出常量测试:React.FunctionComponent< ITestrops和Htmlat贡品 >=({children,className,custom,…rest})=>( {children}{custom} ); 用法: <

是否有一种方法允许下面的React组件上的动态
数据-*
属性与Typescript一起使用?我希望能够:

  • 支持
    类名
    样式
    ,以及其他常见的HTML属性
  • 允许
    数据-*
    属性
  • 允许自定义组件道具,如
    custom
  • 接口ITestProps{
    自定义?:字符串;
    }
    导出常量测试:React.FunctionComponent<
    ITestrops和Htmlat贡品
    >=({children,className,custom,…rest})=>(
    {children}{custom}
    );
    
    用法:

    <Test data-some-random-text="Hello World">test</Test>
    
    测试
    
    与您的想法不同,不。但是您可以让它工作,即使您没有得到有用的类型提示。只需禁用组件的部分或全部(如我所做的)类型检查,并直接处理道具:

    export const Test: React.FunctionComponent<any> = (props: any) => {
        let rest: any = {};
        for (let property in props) {
            if (property.indexOf("data-") === 0) {
                rest[property] = props[property];
            }
        }
    
        return (
            <div className={props.className} {...rest}>
                {props.children} {props.custom}
            </div>
        );
    };
    
    export const Test:React.FunctionComponent=(道具:any)=>{
    让我们休息一下:any={};
    用于(将属性放在道具中){
    if(property.indexOf(“数据-”)==0){
    剩余[属性]=道具[属性];
    }
    }
    返回(
    {props.children}{props.custom}
    );
    };
    
    我的两分钱是,你不应该这样做,要么预定义所有属性,要么传递一个包含所有数据的对象-

    export const Test: React.FunctionComponent<any> = (props: any) => {
        let rest: any = {};
        for (let property in props) {
            if (property.indexOf("data-") === 0) {
                rest[property] = props[property];
            }
        }
    
        return (
            <div className={props.className} {...rest}>
                {props.children} {props.custom}
            </div>
        );
    };