这又是一个极客。我现在正在学习反应。当我试图为我的应用程序创建一个Button
元素时,我在我的代码中发现了这一点。我的想法是根据一个叫做type
的prop
来决定背景颜色。这类似于开关箱。请通读代码查找问题
const colors = {
primary: "#0d6efd",
secondary: "#adb5bd",
success: "#198754",
info: "#0dcaf0",
warning: "#ffc107",
danger: "#dc3545",
light: "#f8f9fa",
dark: "#212529",
};
let bg = ((cl) => {
colors[cl] || "#adb5bd";
})("primary");
let bg2 = ((cl) => colors[cl] || "#adb5bd")(type);
console.log(bg, bg2);
在控制台中,
undefined '#adb5bd'
我错过什么了吗?
您没有返回任何内容。你可以使用
let bg = ((cl) => colors[cl] || "#adb5d")("primary");
您没有从函数返回任何内容。当您在编写函数时使用花括号符号时,您需要显式返回。
let bg = ((cl) => {
return colors[cl] || "#adb5bd";
})("primary");
我认为最简单的方法是:
const Button = (props) => {
const { type = 'primary' } = props; // we get the type with destructuring
const colors = {
primary: "#0d6efd",
secondary: "#adb5bd",
success: "#198754",
info: "#0dcaf0",
warning: "#ffc107",
danger: "#dc3545",
light: "#f8f9fa",
dark: "#212529",
};
const color = colors[type];
return <button style={{backgroundColor: color}}>I am the button with random color</button>
}