Для пункта # 1, вы можете использовать e.target.checked
для проверки истинного / ложного статуса для определенного CustomInput
;Отметьте этот стек , чтобы увидеть, как он работает
Для пункта №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
- вам нужно создать экземпляр Log in состояния в contstructor
- функция
customInputSwitched
должна передавать аргумент конкретной кнопки, а не жестко закодированный 'button1' - поэтому мы добавляем индексный номерболезни - идентификатор всех кнопок не может быть одинаковым 'exampleCustomSwitch', поэтому мы просто добавляем индексный номер к идентификатору
- . Лучшая практика в отображении, так как массив должен включатьтакже индекс, который имеет преимущества (как показано в следующих 2 пунктах)
соответствующий рабочий JS для вашего кода / stackblitz:
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>
);
}
}