reactjs - Especificar ciertas etiquetas HTML como componentes estilizados genéricos en TypeScript
Intenté construir un componente de estilo genérico con Emotion como encabezado en React con TypeScript. El objetivo es pasar dinámicamente la etiqueta HTML como props, que solo debería ser un "h1" | "h2" | "h3" | "h4" | "h5" | "h6". Este es mi código:
interface Props extends StyledProps {
tag: keyof JSX.IntrinsicElements; // TODO specify only heading
}
export const CenteredHeadline: React.FC<Props> = ({
tag,
fontSizeMobile,
fontSizeDesktop,
children,
}) => {
const StyledComponent = styled(tag)<StyledProps>`
label: CenteredHeadline;
color: #3f4846;
font-size: ${(props) => (props.fontSizeMobile ? 'props.fontSizeMobile' : '34px')};
text-align: center;
@media screen and (min-width: 768px) {
font-size: ${(props) => (props.fontSizeDesktop ? 'props.fontSizeDesktop' : '40px')};
max-width: 750px;
}
`;
return (
<StyledComponent fontSizeMobile={fontSizeMobile} fontSizeDesktop={fontSizeDesktop}>
{children}
</StyledComponent>
);
};
El código anterior funciona bien hasta ahora, pero la propiedad tag no se limita a ser solo un encabezado.
Intenté algo así
interface Props extends StyledProps {
tag:
| JSX.IntrinsicElements['h1']
| JSX.IntrinsicElements['h2']
| JSX.IntrinsicElements['h3']
| JSX.IntrinsicElements['h4']
| JSX.IntrinsicElements['h5']
| JSX.IntrinsicElements['h6']; // TODO specify only heading
}
lo que llevó a un montón de errores en mi propiedad de emoción (etiqueta).
Así que la pregunta está más relacionada con TypeScript, supongo:
¿Hay una manera de especificar ciertas claves en keyof something, JSX.IntrinsicElements en mi caso?
¡Gracias por cualquier ayuda!
ACTUALIZACIÓN
Encuentro una manera de especificar las teclas:
type Tag = Pick<JSX.IntrinsicElements, "h1" | "h2">
const StyledComponent = styled<Tag>(tag)<StyledProps>`
...
Pero recibiré un error en mi componente con estilo que dice
El tipo 'Tag' no cumple con la restricción 'keyof IntrinsicElements'
Entonces supongo que el problema ahora se envía a la emoción.
Todavía estoy feliz por cualquier consejo aquí. =)
Respuesta #1
¿Por qué no simplemente: type Tag="h1" | "h2" | "h3" | ....