【发布时间】:2019-08-16 07:33:01
【问题描述】:
我一直在尝试将类动态设置为单选按钮,但我无法这样做。我有点维护一个带有单选按钮“启用,挂起,禁用”的开关。基于单选按钮选择,我正在尝试分配类名来更改颜色。
我们将不胜感激。
沙盒:https://codesandbox.io/s/complex-logic-to-map-an-array-rkspo
应用
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
switchValue: "pending"
};
this.handleButtonChange = this.handleButtonChange.bind(this);
}
handleButtonChange(event) {
this.setState(
{
switchValue: event.target.value
},
() => {
console.log(this.state.switchValue);
}
);
}
render() {
const { switchValue } = this.state;
return (
<div className={"switch-toggle"}>
<input
type="radio"
onChange={this.handleButtonChange}
name={"disabled"}
value={"disabled"}
checked={switchValue === "disabled" ? true : false}
/>{" "}
<label className={switchValue === "disabled" ? "switch-red" : ""}>
DISABLED
</label>
<input
type="radio"
onChange={this.handleButtonChange}
name={"pending"}
value={"pending"}
checked={switchValue === "pending" ? true : false}
/>{" "}
<label className={switchValue === "pending" ? "switch-pending" : ""}>
PENDING
</label>
<input
type="radio"
onChange={this.handleButtonChange}
name={"enabled"}
value={"enabled"}
checked={switchValue === "enabled" ? true : false}
/>{" "}
<label className={switchValue === "enabled" ? "switch-green" : ""}>
ENABLED
</label>
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
CSS
.switch-toggle {
float: left;
background: #242729;
}
.switch-toggle input {
position: absolute;
opacity: 0;
}
.switch-toggle input + label {
padding: 7px;
float: left;
color: #fff;
cursor: pointer;
}
.switch-pending {
background: grey;
}
.switch-disabled {
background: red;
}
.switch-enabled {
background: green;
}
【问题讨论】:
-
嗯,只是想知道,如果您甚至无法看到输入,为什么还要制作收音机?
-
另外,您在组件中使用“switch-red”作为类名,但您的 CSS 文件中没有该名称。据我所见,它是“开关禁用”的,它似乎工作。另外,我同意@ChristopherNgo,很难找到那些按钮!
标签: javascript html css reactjs setstate