gpt4 book ai didi

reactjs - 如何使用 TypeScript 正确扩展样式化组件

转载 作者:搜寻专家 更新时间:2023-10-30 21:34:59 25 4
gpt4 key购买 nike

根据 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};
`;

关于reactjs - 如何使用 TypeScript 正确扩展样式化组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52919720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com