reactjs - 样式化组件 w/o defaultProps w/ typescript
问题描述
我正在将 React 样式组件库更新为:
- 应用 TypeScript (v4.1)
- 消除 defaultProps 的使用(因为它显然在 React 折旧列表中)
我正在就关于 Typescript 的新模式寻求一般建议,我知道可能有更好的方法来处理默认道具。只是寻找对不同替代方案的有意义的讨论。谢谢!
// theme comes from styled-componets theme prover and is typed
// Typing
type Clr = 'red' | 'blue' | 'green'
type Int = 'L' | 'D'
type TBox = {
clr: Clr,
int: Int,
}
interface IBox {
clr: Clr,
int: Int,
children: JsxElement[]
}
// OLD Pattern - using defaultProps
export const Box = styled.div<IBox>`
background-color : ${({theme, clr, int})=>theme.fnt.clr[clr][int]};
height: 50px;
width: 100px;
`
Box.defaultProps = {
clr: 'green',
int: 'D'
}
// NEW Pattern - without defaultProps - using a wrapper
export const Box2A: (props: Readonly<Partial<IBox>>) => JSX.Element = (props) => {
return <Box2Style {...Box2DefaultProps} {...props} />;
};
const Box2Style = styled.div<TBox>`
background-color : ${({theme, clr, int})=>theme.fnt.clr[clr][int]};
height: 50px;
width: 100px;
`
const Box2DefaultProps: TBox = {
clr: 'green',
int: 'D'
}
解决方案
为了避免不必要的包装器将一些道具传递给渲染的组件或元素,您可以使用
.attrs
构造函数。它允许您将其他道具(或“属性”)附加到组件。
export const Box = styled.div<TBox>` // can use IBox interface or TBox type
background-color : ${({ theme, clr, int }) => theme.fnt.clr[clr][int]};
height: 50px;
width: 100px;
`
Box.defaultProps = {
clr: 'green',
int: 'D'
}
成为
export const Box = styled.div.attrs<TBox>(({ clr, int }) => ({
clr: clr || 'green',
int: int || 'D',
}))<TBox>` // can use IBox interface or TBox type
background-color : ${({ theme, clr, int }) => theme.fnt.clr[clr][int]};
height: 50px;
width: 100px;
`
或者
export const Box = styled.div.attrs<TBox>(({ clr = "green", int = "D" }) => ({
clr,
int,
}))<TBox>` // can use IBox interface or TBox type
background-color : ${({ theme, clr, int }) => theme.fnt.clr[clr][int]};
height: 50px;
width: 100px;
`
无论如何,我都不是打字稿专家,因此可能需要调整界面,并且我发现了一个关于打字稿和语法的封闭 github问题。.attrs
推荐阅读
- php - 如何将 Varnish ESI 与模块化 PHP 模板系统一起使用
- ios - 经常重新计算路线的问题
- python - Coverage 无法将“manage.py”作为 Python 代码运行
- servicestack - ServiceStack ApiKey
- javascript - 用于创建幻灯片元素的 setInterval setTimeout 延迟和暂停
- python - 如何获取复选框值以保存到文本文件中?
- python-3.x - Python reading lines in a txt file and writing to new txt file
- java - 如何减少按钮点击区域(仅限按钮)
- python - 如何将多个变量传递给常规(re.search)表达式
- android - 当用户单击来自不同应用程序的任何链接时,想要在 android 应用程序选择器对话框中列出我的应用程序