gpt4 book ai didi

css - 条件 Prop 内的样式化组件 Prop

转载 作者:太空宇宙 更新时间:2023-11-04 05:44:31 27 4
gpt4 key购买 nike

我的样式组件代码:

import React, { Component } from "react";
import PropTypes from "prop-types";
import styled, { ThemeProvider } from "styled-components";

import { theme } from "../shared/theme";

const ContainerDiv = styled.div`
padding-bottom: ${props => props.theme.paddings.text.small};
padding-top: ${props => props.theme.paddings.text.small};
padding-left: ${props => props.theme.paddings.text.normal};
padding-right: ${props => props.theme.paddings.text.normal};
font-size: ${props => {
if (props.bigLabel && props.bigLabel === true)
return props.theme.typography.sizes.big;

return props.theme.typography.sizes.normal;
}};
width: 100%;
font-weight: ${props =>
props.bold && props.bold === true ? "bold" : "normal"};
${props =>
props.type &&
props.type === "danger" &&
`
color: ${props => props.theme.colors.text.danger};
`}
${props =>
props.type &&
props.type === "primary" &&
`
color: ${props => props.theme.colors.text.primary};
`}
`;

class Text extends Component {
static propTypes = {
href: PropTypes.string,
bold: PropTypes.bool,
paragraph: PropTypes.bool,
type: PropTypes.string
};

render = () => {
let { href, bold, paragraph, type } = this.props;

let content = this.props.children;
if (paragraph && paragraph === true) content = <p>{content}</p>;

return (
<ThemeProvider theme={theme}>
<ContainerDiv href={href} bold={bold} type={type}>
{content}
</ContainerDiv>
</ThemeProvider>
);
};
}

export default Text;

使用 type 属性应该改变文本颜色,但在我的测试中没有应用所需的颜色:

<Text type="primary">Primary text</Text>
<Text type="danger">Danger text</Text>

在这两种情况下,颜色都保持默认颜色。

如何根据我的 type 属性正确设置文本颜色?

最佳答案

${props => 声明中使用 props 时,您不需要在内部函数中调用该函数,因为您可以访问 props 来自外部函数调用。

所以这样:

${props =>
props.type &&
props.type === "danger" &&
`
color: ${props => props.theme.colors.text.danger};
`}

会变成这样:

${props =>
props.type &&
props.type === "danger" &&
`
color: ${props.theme.colors.text.danger};
`}

注意 color 现在是 color: ${props.theme.colors.text.danger}; 而不是 color: ${props => props .theme.colors.text.danger

此外,我会考虑另一个 prop 名称而不是 type,因为这会导致 type 呈现到 HTML 中的 DOM(因为 type 是一个有效的 HTML 属性)。


另请注意,您可以安全地只检查 props.type === "danger" 而不是首先检查 props.type 是否存在,结果是一样的。

所以 ${props => props.type === "danger"&& ...你的风格

关于css - 条件 Prop 内的样式化组件 Prop ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58844188/

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