javascript - 我如何通过反应动态地将道具作为变量分配给我自己在 scss/css 中的颜色托盘中的颜色?
问题描述
我正在使用以下道具调用组件“MyRadioButton”:
<MyRadioButton
label="Radio Group"
theme="custom-red" //this line
error="Field is required "
radioBtns={options}
id="radioBtns"
name="radioBtns"
getValue={this.getValue}
/>
我创建了一个反应组件“MyRadioButton”,它将接受颜色名称(主题)作为道具。
export const MyRadioButton = props => {
const {theme} = props;
return (
<div className="my-radio-buttons"> // need to use theme here
<input
onChange={onChange}
type="radio"
/>
</div>
)}
基于这个道具,我想在我的组件 scss 文件中分配变量,它将从我自定义的颜色托盘中获取颜色代码。
我的单选按钮.scss
/* custom color pallet */
$custom-orange: #F060D6;
$custom-red: #BB532E;
$custom-blue: #4C9FEB;
.my-radio-buttons {
.input{
border: 2px solid $custom-red; // i want to assign the color variable based on input prop value to this property
}
}
我已经尝试使用 javascript 在 css root 设置变量并使用变量函数 var() 访问它,它工作正常。但由于一些限制,我不想使用这种方法。还因为颜色托盘列表很大,我不想为所有这些使用单独的类。
我正在寻找其他解决方案或不同的方法。
解决方案
因此,您可以使用自定义 css 变量和您传递的主题属性的组合。在您的 css 中,您将定义边框的基色,例如:
.my-radio-buttons {
--theme-color: red;
input {
border: 2px solid var(--theme-color);
}
}
这可以由您的组件通过componentDidMount
或useEffect
使用传递的主题更新:
const MyRadioButton = props => {
const { theme } = props;
React.useEffect(() => {
const input = document.querySelector(".my-radio-buttons input");
input.style.setProperty("--theme-color", props.theme);
}, []);
return (
<div className="my-radio-buttons">
<input />
</div>
);
};
根据您的代码风格,您可以将 替换querySelector
为ref
.
推荐阅读
- php - 在克隆两个输入字段时激活 JS 功能
- python - 从另一个 python 文件导入函数
- extjs - sencha extjs 中的疯狂拖放
- c# - 如果主窗口未显示在任务栏中,如何在调用 Process.CloseWindow() 后获得通知
- c++ - window.display() 单独在显示的最后一个缓冲区和当前缓冲区之间切换
- android - 在 Cordova Android 中,Font Awesome 对触摸无响应
- python - 有人能告诉我最后一个循环在做什么吗?
- python-3.x - 在张量流中获取批次
- java - 获取 LocationSettingsResult 时出现 DEVELOPER_ERROR (statusCode=10)
- selenium - 显式等待与页面工厂元素一起等待很长时间才能响应