gpt4 book ai didi

reactjs - 更改 radio 输入时如何更改标签样式?

转载 作者:行者123 更新时间:2023-12-04 07:16:15 25 4
gpt4 key购买 nike

我创建了 className "OccupancyChecked",所以它会被应用到被检查的 radio 的标签上,但由于某种原因我不能让它工作。
这是样式:

const Occupancy = styled.label`
//more code

.OccupancyChecked {
border: 1px solid rgba(255, 255, 255, 0.24);
background: #7f5cf1;
}
`;
下面是调用上面的className的代码。我试图做的是:只有两个 radio ,所以我插入了一个 onChange在第一个 radio 上,结果在每个标签的 className 中,它应该调用 "Occupancy" className 如果 radio 是 checked否则为空 className。我相信这个逻辑应该有效,但事实并非如此。我还创建了一个 sandbox所以我可以显示正在运行的代码。
export default function App() {
const [occupancyChecked, setOccupancyChecked] = useState(0);

function changeOccupancyChecked() {
occupancyChecked === 0 ? setOccupancyChecked(1) : setOccupancyChecked(0);
return;
}

return (
<div className="App">
<Occupancy>
<label
htmlFor="radioTeacher"
className={occupancyChecked === 0 ? "OccupancyChecked" : ""}
>
<input
type="radio"
name="occupancy"
id="radioTeacher"
onChange={changeOccupancyChecked}
checked
/>
<span>I'm a teacher</span>
</label>
<label
htmlFor="radioStudant"
className={occupancyChecked === 1 ? "OccupancyChecked" : ""}
>
<input type="radio" name="occupancy" id="radioStudant" />
<span>I'm a studant</span>
</label>
</Occupancy>
</div>
);
}
如何解决这个问题?显示类名 OccupancyChecked在选中的 radio 中。

最佳答案

默认 checked在 radio 教师是主要原因。我已经更新了它以便更好地理解。
Working link

import "./styles.css";
import styled from "styled-components";
import { useEffect, useState } from "react";

const Occupancy = styled.label`
display: flex;
justify-content: space-between;
margin-bottom: 1rem;
font-size: 0.7rem;
font-family: "Open Sans", sans-serif;
font-weight: 400;

label {
border: 1px solid #6f49ed;
background: #6f49ed;
border-radius: 4px;
padding: 1rem;
text-transform: uppercase;
width: 48%;

input {
}

span {
margin-left: 0.4rem;
}
}
.OccupancyChecked {
border: 1px solid rgba(255, 255, 255, 0.24);
background: red;
}
`;

export default function App() {
const [occupancyChecked, setOccupancyChecked] = useState(0);

const changeOccupancyChecked = (val) => {
console.log("Value to set:", val);
setOccupancyChecked(val);
//occupancyChecked === 0 ? setOccupancyChecked(1) : setOccupancyChecked(0);
//return;
};

return (
<div className="App">
<Occupancy>
<label
htmlFor="radioTeacher"
className={occupancyChecked === 0 ? "OccupancyChecked" : ""}
>
<input
type="radio"
name="occupancy"
id="radioTeacher"
onChange={() => {
changeOccupancyChecked(0);
}}
/>
<span>I'm a teacher</span>
</label>
<label
htmlFor="radioStudant"
className={occupancyChecked === 1 ? "OccupancyChecked" : ""}
>
<input
type="radio"
name="occupancy"
id="radioStudant"
onChange={() => {
changeOccupancyChecked(1);
}}
/>
<span>I'm a studant</span>
</label>
</Occupancy>
</div>
);
}

关于reactjs - 更改 radio 输入时如何更改标签样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68735078/

25 4 0