如何使用对象,我得到的字符串在道具


const dark = { backgroundColor: "#2c3343", color: "#c8e5c9" };
const light = { backgroundColor: "white", color: "black" };
return (
<>
<div className="my-5 container">
<h1>{props.heading}</h1>
<div className="mb-3">
<textarea
className="form-control"
id="myBox"
value={text}
rows={8}
onChange={handleOnChange}
style={{
backgroundColor: props.mode.backgroundColor,
color: props.mode.color,
}}
>
asd
</textarea>
</div>
</div>
</>
);

基本上我在这个js文件中的props传递模式。Mode是一个字符串,可以是'light'或'dark'。在道具的基础上。模式值,我想改变文本框的颜色。但是css样式不会发生在上面。该怎么办?我在调用对象时做错了什么吗?就像我想让它这样工作:-

(考虑mode == 'dark')

style = {{
backgroundColor: dark.backgroundColor,
color: dark.color,
}}

考虑模式为'light'

style = {{
backgroundColor: light.backgroundColor,
color: light.color,
}}

我所做的亮的和暗的物体也给了我没有使用它们的警告。我知道我可以使用三元运算符,而不是创建两个单独的对象,然后调用它们的值,但我想这样做。所以,如果有人能指出这个问题,我会很感激。这是我的部分代码:-

const dark = {
backgroundColor: "#2c3343",
color: "#c8e5c9",
};
const light = {
backgroundColor: "white",
color: "black",
};
return (
<>
<div className="my-5 container">
<h1>{props.heading}</h1>
<div className="mb-3">
<textarea
className="form-control"
id="myBox"
value={text}
rows={8}
onChange={handleOnChange}
style={{
backgroundColor: props.mode.backgroundColor,
color: props.mode.color,
}}

可以使用方括号语法动态访问对象上的值。

const modes = {
light: {...},
dark: {...},
};
const thisMode = modes[props.mode];
// now use it like
color: thisMode.color

你需要动态使用CSS,所以我已经更新了你的代码,它应该为你工作。

const customColor = {
dark: {
backgroundColor: "#2c3343",
color: "#c8e5c9",
},
light: {
backgroundColor: "white",
color: "black",
}
}
return (
<>
<div className="my-5 container">
<h1>{props.heading}</h1>
<div className="mb-3">
<textarea
className="form-control"
id="myBox"
value={text}
rows={8}
onChange={handleOnChange}
style={customColor[props.mode]}
/>
</div>
</div>
</>)

你可以按照@windowsill提到的方法去做,或者按照下面的方法去做。

style={
props.mode === "light"
? {
backgroundColor: light.backgroundColor,
color: light.color,
}
: {
backgroundColor: dark.backgroundColor,
color: dark.color,
}
}

最新更新