我有一个很长的复选框列表(没有优化),我想让它们处于一种状态(选中的那个),我真的不确定如何处理它,希望得到帮助(也应该在单击时处理取消选中)……
<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>
发布于 2020-11-30 00:18:33
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>
);
}
}发布于 2020-11-29 21:47:11
就是这样:
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>
);
}
}https://stackoverflow.com/questions/65060268
复制相似问题