首页 > 解决方案 > 如何在 React 中的按钮组件中实现颜色

问题描述

我想在我的按钮组件中实现一个颜色选项以在我的所有全局组件中使用它,这样我就可以动态更改文本和颜色

这是正确的吗?

import React from 'react';
import './Button.css';

const Button = ({text, BtnVersion1}) => {


    return (
        <a href="#" style={{color: {BtnVersion1}}} className="buy">{text}</a>
    )
}

export default Button;


<Button style={{color: "red"}} text="SHOP NOW" />

标签: javascripthtmlcssreactjs

解决方案


这是样式化组件非常有用的地方。在组件上声明“样式”的地方,这是一种内联样式,并且仅存在于该按钮的该实例上。您可以传递一个道具,例如“btnColor”给样式化组件用来更改颜色的按钮。见下文。

import React from 'react';
import styled from 'styled-component';
import './Button.css';

const StyledButton = styled.a`
   background-color: ${props => props.btnColor ? props.btnColor : 'red'};
`

const Button = ({
   text, 
   btnColor
}) => {
    return (
        <StyledButton href="#" btnColor={btnColor} className="buy">{text}</StyledButton>
    )
}

export default Button;


<Button btnColor='red' text="SHOP NOW" />

您可以在上面的 StyledButton 中看到,如果我们提供 btnColor 属性而不是使用该颜色,则默认为“红色”。

有关样式化组件的更多信息 - https://styled-components.com/


推荐阅读