如何使用样式组件中的道具类型?
How to use props type from a styled component?
有时我的组件样式如下:
import styled from 'styled-components';
const StyledButton = styled.button;
然后我需要像这样使用它
export default function CloseButton() {
return <StyledButton>Close</StyledButton>
}
并像 <CloseButton />
一样使用它。
但是如果我需要像<CloseButton onClick={doSomething} />
那样使用它呢?
我必须将 CloseButton
组件更改为:
type Props = {
onClick: () => void;
}
export default function CloseButton(props: Props) {
return <StyledButton onClick={props.onClick}>Close</StyledButton>
}
这很糟糕。所以更好的方法是传递所有道具,例如:
export default function CloseButton(props: any) {
return <StyledButton {...props}>Close</StyledButton>
}
这很干净简单...但是如何避免 any
类型的 props
并告诉打字稿使用 StyledButton 中的道具?
使用 Typescript,您可以通过其键访问类型字段类型,如下所示:
type MyObject = {
value: number;
}
// same as : number
const v: MyObject['value'] = 6;
在你的情况下,你想要什么:
export default function CloseButton(props: StyledButton['props']) {
return <StyledButton {...props}>Close</StyledButton>
}
当你想保持一个类型的范围,但允许从另一个类型使用它时,它非常有用。
好像是这样的:
export default function CloseButton(props: typeof StyledButton.defaultProps) {
return <StyledButton {...props}>Close</StyledButton>
}
工作近乎完美。它确实显示了 <button>
元素的 HTML 属性,尽管它没有显示像 as and forwardAs
这样的 StyledComponents 道具
有时我的组件样式如下:
import styled from 'styled-components';
const StyledButton = styled.button;
然后我需要像这样使用它
export default function CloseButton() {
return <StyledButton>Close</StyledButton>
}
并像 <CloseButton />
一样使用它。
但是如果我需要像<CloseButton onClick={doSomething} />
那样使用它呢?
我必须将 CloseButton
组件更改为:
type Props = {
onClick: () => void;
}
export default function CloseButton(props: Props) {
return <StyledButton onClick={props.onClick}>Close</StyledButton>
}
这很糟糕。所以更好的方法是传递所有道具,例如:
export default function CloseButton(props: any) {
return <StyledButton {...props}>Close</StyledButton>
}
这很干净简单...但是如何避免 any
类型的 props
并告诉打字稿使用 StyledButton 中的道具?
使用 Typescript,您可以通过其键访问类型字段类型,如下所示:
type MyObject = {
value: number;
}
// same as : number
const v: MyObject['value'] = 6;
在你的情况下,你想要什么:
export default function CloseButton(props: StyledButton['props']) {
return <StyledButton {...props}>Close</StyledButton>
}
当你想保持一个类型的范围,但允许从另一个类型使用它时,它非常有用。
好像是这样的:
export default function CloseButton(props: typeof StyledButton.defaultProps) {
return <StyledButton {...props}>Close</StyledButton>
}
工作近乎完美。它确实显示了 <button>
元素的 HTML 属性,尽管它没有显示像 as and forwardAs