reactjs - 如何使用 TypeScript 正确扩展样式化组件
问题描述
根据 styled-components v4,.extend
已弃用,扩展或组合组件的正确方法是:
const ButtonA = styled('button')`color: ${props => props.color};`
const ButtonB = styled(ButtonA)`background: 'white';`
但是我找不到使用 TS 执行此操作的正确方法,因为我遇到了一些错误,例如:
import styled from "styled-components";
// Let's create ButtonA
type ButtonAProps = { a: string };
const ButtonA = styled<ButtonAProps, "button">("button")`
color: ${props => props.a};
`;
// So, here is what I've tried
// Fail #1
// =======
type ButtonBProps = { b: string };
const ButtonB = styled<ButtonBProps, ButtonAProps>(ButtonA)`
background: ${props => props.b};
`; // Here I get autocompletion only for B props :(
const Test = () => <ButtonB a="something" />; // And here I get autocompletion only for A props :(
// Fail #2
// =======
type ButtonBProps = { b: string } & ButtonAProps;
const ButtonB = styled<ButtonBProps, ButtonAProps>(ButtonA)`
background: ${props => props.b};
`; // Here I get autocompletion for A & B props, good!
const Test = () => <ButtonB a="something" />; // Here I still get autocompletion only for A props :(
// Fail #3
// =======
type ButtonBProps = { b: string } & ButtonAProps;
const ButtonB = styled<ButtonBProps, ButtonBProps>(ButtonA)` // Property 'b' is missing in type 'ButtonAProps', of course
background: ${props => props.b};
`; // Here I get "props has implicitly any type"
const Test = () => <ButtonB />; // Here I don't get any type checking at all
似乎快到了,但无法弄清楚。
有什么建议吗?谢谢!
解决方案
截至 2019 年 9 月,以下代码也有效:
// First extend ButtonAProps with an additional prop
interface ButtonBProps extends ButtonAProps {
b:string;
}
// ButtonB Component
const ButtonB = styled(ButtonA)<ButtonBProps>`
background: ${props => props.b};
`;
推荐阅读
- python - 在同一类的不同实例之间实现逻辑
- postgresql - 如何在 Postgres 中为指定(分区)表禁用一个查询
- python - 如何根据来自 for 循环的值制作多维列表
- google-chrome - 将整个网页投射到电视上?
- python - 如何动态改变芹菜节拍的时间表?
- c++ - curl_easy_perform 失败:从 Swift 调用时 URL 使用错误/非法格式或缺少 URL
- node.js - 猫鼬转换 & 到 &
- css - 如何将 box-shadow 更改为 css 中的类似命令?
- r - R dplyr:过滤数据框以获取列唯一值的向量
- javascript - 在本机反应中添加谷歌登录库时出错