我想让框得到颜色,但只有一个我点击,其余的应该有默认的一个。然后,当我点击下一个,前一个框应该回到默认的颜色。目前,当我点击其中一个,所有的框得到不需要的背景颜色。我知道我基本上通过了&;color&;每个道具都有颜色,因为道具和状态都是一样的。但是如何在不改变道具名称的情况下正确地使用一个状态?
const {useState} = React;
const App = () => {
const [color, setColor] = useState("");
const firstBox = () => {
setColor("firstBox");
};
const secondBox = () => {
setColor("secondBox");
};
const thirdBox = () => {
setColor("thirdBox");
};
return (
<div className="container">
<Box setColor={firstBox} color={color} />
<Box setColor={secondBox} color={color} />
<Box setColor={thirdBox} color={color} />
</div>
);
}
const Box = ({ setColor, color }) => {
return (
<div
onClick={setColor}
className={`box ${
color === "firstBox" || color === "secondBox" || color === "thirdBox"
? "active"
: ""
}
`}
></div>
);
};
ReactDOM.createRoot(
document.getElementById("root")
).render(
<App/>
);
body {
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.container {
display: flex;
gap: 2rem;
}
.box {
width: 250px;
height: 250px;
background: lightblue;
}
.active {
background: red;
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
有多种方法可以做到这一点,但这是我要做的:
const {useState} = React;
const App = () => {
const [color, setColor] = useState("");
return (
<div className="container">
<Box setColor={() => setColor('First Box')} selected={color === 'First Box'} />
<Box setColor={() => setColor('Second Box')} selected={color === 'Second Box'} />
<Box setColor={() => setColor('Third Box')} selected={color === 'Third Box'} />
</div>
);
}
const Box = ({ setColor, selected }) => {
return (
<div
onClick={setColor}
className={selected ? 'active box' : 'box'}
/>
);
};
ReactDOM.createRoot(
document.getElementById("root")
).render(
<App/>
);
既然你问了,你不想使用任何额外的道具或状态。你所要做的就是把Box组件代码改成
const Box = ({ setColor, color }) => {
return (
<div
onClick={setColor}
className={`box ${setColor.name === color ? "active" : ""}
`}
></div>
);
};