如何使用 react 在 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 文件中分配变量,该文件将从我的自定义调色板中获取颜色代码。

my-radio-button.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 根目录设置变量并使用变量函数 var(( 访问它,它工作正常。 但由于一些限制,我不想使用这种方法。 另外,由于调色板列表很大,我不想对所有调色板使用单独的类。

我正在寻找其他解决方案或不同的方法。

因此,您可以使用自定义 css 变量和传递的主题属性的组合。在 css 中,您可以定义边框的基色,例如:

.my-radio-buttons {
--theme-color: red;
input {
border: 2px solid var(--theme-color);
}
}

这可以通过您的组件通过传递的主题componentDidMountuseEffect进行更新:

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

最新更新