如何在现有SolidJS元素的SolidJS道具中进行扩展,并在下面的示例中创建与此ButtonProps接口类似的自定义接口,以便作出反应。
import React from 'react';
interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
title: string;
showIcon: boolean;
}
const Button: React.FC<ButtonProps> = ({ title, showIcon, ...props }) => {
return (
<button {...props}>
{title}
{showIcon && <Icon/>}
</button>
);
};发布于 2022-05-05 11:21:30
同样,除了您需要避免对反应性属性进行析构并使用splitProps之外,您的示例将转换为:
import { splitProps, JSX } from 'solid-js';
interface ButtonProps extends JSX.ButtonHTMLAttributes<HTMLButtonElement> {
title: string;
// better make that optional, so you can use Button without having to
// add the showIcon attribute:
showIcon?: boolean;
}
const Button = (props: ButtonProps) => {
const [local, buttonProps] = splitProps(props, ['title', 'showIcon']);
return (
<button {...buttonProps}>
{local.title}
{local.showIcon && <Icon/>}
</button>
);
};如您所见,内部元素属性的类型在JSX中,来自JSX -dom-表达式,该表达式将JSX转换为solid中的反应性表达式。
发布于 2022-05-05 11:17:12
我通常是这样做的:
import type { Component, JSX } from "solid-js";
import { splitProps } from "solid-js";
export type ButtonProps = {
title: string;
showIcon: boolean;
} & JSX.HTMLAttributes<HTMLButtonElement>;
const Button: Component<ButtonProps> = (props) => {
const [, rest] = splitProps(props, ["title", "showIcon"]);
return (
<button {...rest}>
{props.title}
{props.showIcon && <Icon/>}
</button>
);
}我在示例中使用了一个类型交集,但是您可以通过扩展接口来完成同样的任务。
我在这里使用的是Component类型,默认情况下,它还为道具添加了一个可选的children支柱,不过我认为随着1.4版本的发布,这种情况会发生变化。
我还使用splitProps方法来帮助避免破坏,从而保留对支柱值的反应性更新。
https://stackoverflow.com/questions/72126059
复制相似问题