javascript - 如何在 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" />
解决方案
这是样式化组件非常有用的地方。在组件上声明“样式”的地方,这是一种内联样式,并且仅存在于该按钮的该实例上。您可以传递一个道具,例如“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/
推荐阅读
- google-apps-script - 在谷歌表格中使用 setConditionalFormatRules() 突出显示一行
- python - 像 COCO 一样自动创建图像蒙版
- python - conv2D 中的填充
- sendkeys - 特殊键 Ctrl+A+DEL 在 BluePrism 中不起作用
- python - 在 PyTorch 中实现完全连接层的 dropout
- php - PHP MongoDB\..\ServerException 无法使用数据库“模型”发送“getMore”命令:套接字错误或超时
- unity3d - 既然不管理内存,Unity WebGL heap总是必然会崩溃?
- python - Pandas 如何对每一行中的连接字符串进行排序?
- macos - 如何验证音频数据是否有效?
- go - golang中通过接口{}的通用结构映射