[英]HandleCheckBox react checked and unchecked , get a list into a state
我有一長串復選框(沒有優化),我想讓它們處於一個狀態(選中的那個),我不確定如何處理它希望得到幫助(點擊時也應該處理取消選中).. .
<div className=' row float-center d-flex justify-content-center '> <label className='m-3'> <input name='1' type='checkbox' checked={this.state.isGoing} onChange={this.handleInputChange} /> 1 </label> <label className=' m-3'> <input name='1.5' type='checkbox' checked={this.state.isGoing} onChange={this.handleInputChange} /> 1.5 </label> </div>
class Human extends React.Component {
constructor(props) {
super(props);
this.state = {
checkState: {
isGoing1: false,
isGoing2: false
}
};
}
handleInputChange = (event) => {
this.setState({
...this.state,
checkState: {
...this.state.checkState,
[event.target.name]: event.target.checked
}
});
};
render() {
return (
<div className=" row float-center d-flex justify-content-center ">
<label className="m-3">
<input
name="isGoing1"
type="checkbox"
checked={this.state.isGoing1}
onChange={this.handleInputChange}
/>
1
</label>
<label className=" m-3">
<input
name="isGoing2"
type="checkbox"
checked={this.state.isGoing2}
onChange={this.handleInputChange}
/>
1.5
</label>
</div>
);
}
}
就是這個:
import React, { Component, Fragment } from "react";
import "./style.css";
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = { isGoing1: false, isGoing2: false };
this.handleInputChange1 = this.handleInputChange1.bind(this);
this.handleInputChange2 = this.handleInputChange2.bind(this);
}
componentDidMount() {
this.setState({ isGoing1: false });
this.setState({ isGoing2: false });
}
componentWillUnmount() {
this.setState({ isGoing1: false });
this.setState({ isGoing2: false });
}
componentDidUpdate(prevProps) {
console.log("isGoing1" + this.state.isGoing1);
console.log("isGoing2" + this.state.isGoing2);
}
handleInputChange1 = () => {
this.setState(state => ({
isGoing1: !state.isGoing1
}));
};
handleInputChange2 = () => {
this.setState(state => ({
isGoing2: !state.isGoing2
}));
};
render() {
return (
<div className=" row float-center d-flex justify-content-center ">
<label className="m-3">
<input
name="1"
type="checkbox"
checked={this.state.isGoing1}
onChange={this.handleInputChange1}
/>
1
</label>
<label className=" m-3">
<input
name="1.5"
type="checkbox"
checked={this.state.isGoing2}
onChange={this.handleInputChange2}
/>
1.5
</label>
</div>
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.