styled component的defaultProps配置值未被正确读取问题
问题根源
你对defaultProps的作用理解有误,它只会在你没有主动传入buttonTheme属性的时候,给Button组件的buttonTheme prop赋值为defaultButtonTheme,不会自动合并传入主题和默认主题的内部属性。你现在主动传了buttonTheme="defaultButton",defaultProps根本不会生效,读取buttonTheme.defaultButton.borderValue的时候返回undefined,浏览器会自动使用button标签的默认边框样式,所以才会出现不符合预期的边框。
解决方法
方案1:样式取值时合并默认主题属性
直接在样式的插值函数里,把当前选中的主题和默认主题合并,缺省的属性就会自动使用默认主题的取值:
const Button = styled.button` width: 88px; height: 36px; background:${(props) => ({...buttonTheme.defaultButtonTheme, ...buttonTheme[props.buttonTheme]}).backgroundValue}; box-shadow:${(props) => ({...buttonTheme.defaultButtonTheme, ...buttonTheme[props.buttonTheme]}).boxShadowValue}; border:${(props) => ({...buttonTheme.defaultButtonTheme, ...buttonTheme[props.buttonTheme]}).borderValue} ; border-radius: 6px; margin: 5px 0; `;
如果觉得重复写合并逻辑太冗余,可以封装成通用取值函数:
// 封装主题取值逻辑 const getThemeVal = (propKey) => (props) => { const mergedTheme = {...buttonTheme.defaultButtonTheme, ...buttonTheme[props.buttonTheme]} return mergedTheme[propKey] } const Button = styled.button` width: 88px; height: 36px; background: ${getThemeVal('backgroundValue')}; box-shadow: ${getThemeVal('boxShadowValue')}; border: ${getThemeVal('borderValue')}; border-radius: 6px; margin: 5px 0; `;
方案2:定义主题时直接继承默认配置
在定义各个子主题的时候,直接基于默认主题扩展,从源头上保证每个主题都有全量属性:
const defaultButtonTheme = { borderValue: "0", boxShadowValue: "0", backgroundValue: "0" } const buttonTheme = { defaultButtonTheme, defaultButton: { // 先继承默认配置,再写自定义属性覆盖 ...defaultButtonTheme, backgroundValue: "#E0E0E0", boxShadowValue: "0px 2px 3px rgba(51, 51, 51, 0.2)", color: "#3F3F3F" }, // 其他主题同理,都先展开默认配置再写自定义值 hoverFocusType1Button: { ...defaultButtonTheme, backgroundValue: "#AEAEAE", boxShadowValue: "0px 2px 3px rgba(51, 51, 51, 0.2)", color: "#3F3F3F" }, // 剩余其他主题配置都按这个规则修改即可 }
这种方案更易维护,后续新增主题只要按规则扩展就不会出现缺属性的问题。
内容的提问来源于stack exchange,提问作者vikramvi
相关产品推荐
相关产品推荐

