<FormGroup>
<div>
{this.props.diseases.map((disease, index) => (
<FormGroup>
<CustomInput
type="switch"
id="exampleCustomSwitch"
key={disease}
disease={disease}
onClick={(disease) => this.props.toggle(disease)}
label={disease}
/>
</FormGroup>
))
}
</div>
</FormGroup>
我希望能够找到开关的状态,无论它是打开还是关闭。不知道我该怎么做?我是否要传递某种默认值,将0设置为off,将1设置为on?
当前,这些开关正在从阵列中进行适当的映射,但是打开或关闭仅适用于第一个开关。因此,如果我单击任何其他开关,则由于某种原因,第一个开关会切换。
答案 0 :(得分:0)
对于#1点,y您可以使用e.target.checked
来检查特定CustomInput
的是/否状态;选中this stackblitz即可查看
对于第2点,如果您共享现有代码,则可以更轻松地帮助您解决特定情况
相关的 js :
class App extends Component {
constructor() {
super();
this.state = {
name: "World to React",
log: []
};
this.customInputSwitched.bind(this);
}
customInputSwitched(buttonName, e) {
let newStr = `we received ${e.target.checked} for ${buttonName}...`;
console.log(newStr);
let newLog = [...this.state.log, newStr];
this.setState({ log: newLog });
}
render() {
var testName = "modal for testing - click here";
return (
<div>
<Hello name={this.state.name} />
<p>Start editing to see some magic happen :)</p>
<Form>
<FormGroup>
<Label for="exampleCheckbox">Switches</Label>
<div>
<CustomInput
type="switch"
id="exampleCustomSwitch"
name="customSwitch"
label="Turn on this custom switch"
onChange={this.customInputSwitched.bind(this, "button1")}
/>
<CustomInput
type="switch"
id="exampleCustomSwitch2"
name="customSwitch"
label="Or this one"
onChange={this.customInputSwitched.bind(this, "button2")}
/>
<CustomInput
type="switch"
id="exampleCustomSwitch3"
label="But not this disabled one"
disabled
/>
<CustomInput
type="switch"
id="exampleCustomSwitch4"
label="Can't click this label to turn on!"
htmlFor="exampleCustomSwitch4_X"
disabled
/>
</div>
</FormGroup>
</Form>
{this.state.log}
</div>
);
}
}
更新#1 :鉴于以下提问者的评论
您在https://stackblitz.com/edit/react-rcqlwq的代码中几乎没有问题
customInputSwitched
函数应传递特定按钮的参数,而不是硬编码的“ button1”-因此我们添加了疾病的索引号与您的代码/ stackblitz相关的可运行JS :
class App extends Component {
constructor() {
super();
this.state = {
diseases: [
"Normal",
"Over inflated lungs",
"Pneumonia",
"Pneumothorax",
"Congestive cardiac failure",
"Consolidation",
"Hilar enlargement",
"Medical device",
"Effusion"
],
log: []
};
this.customInputSwitched.bind(this);
}
customInputSwitched(buttonName, e) {
let newStr = `we received ${e.target.checked} for ${buttonName}...`;
console.log(newStr);
let newLog = [...this.state.log, newStr];
this.setState({ log: newLog });
}
render() {
return (
<div>
<p>Start editing to see some magic happen :)</p>
<Form>
<FormGroup>
<Label for="exampleCheckbox">Switches</Label>
{this.state.diseases.map((disease, index) => {
//console.log(disease, index);
let idName = "exampleCustomSwitch"+index;
return (
<div key={index}>
<CustomInput
type="switch"
id={idName}
name="customSwitch"
label={disease}
onChange={this.customInputSwitched.bind(this, "button"+index)}
/>
</div>
);
}
)}
</FormGroup>
</Form>
{this.state.log}
</div>
);
}
}