我想将值添加到React中状态为onClick
事件的数组中。
到目前为止,使用onSelectRooms
函数,我可以使用e.target.id来获取值,但是它不会将该值附加到处于状态的数组selectedRooms
上。
onSelectRooms = (e) => {
const newItem = e.target.id;
this.setState({
selectedRooms: [...this.state.selectedRooms, newItem]});
}
export default class ExportReportRoomSelectionModal extends React.Component {
constructor(props) {
super(props);
const roomOrder = configContext.value.roomOrder;
this.state = {
rooms: roomOrder,
selectedRooms: [],
};
this.onSelectRooms = this.onSelectRooms.bind(this);
}
onSelectRooms = (e) => {
const newItem = e.target.id;
this.setState({
selectedRooms: [...this.state.selectedRooms, newItem]});
}
render() {
return (
<Modal>
<Modal.Header>
<Modal.Title>Title</Modal.Title>
</Modal.Header>
<Modal.Body>
<p>Number of rooms: {this.state.rooms.length}</p>
<p>Rooms:</p>
<Grid fluid={true}>
<Row className="show-grid">
{ this.state.rooms.map((name, i ) =>
<Col key={i}>
<Panel onClick={this.onSelectRooms}>
<Panel.Heading id={name}>
{name}
</Panel.Heading>
</Panel>
</Col>
)}
</Row>
</Grid>
</Modal.Body>
</Modal>);
}
}
答案 0 :(得分:0)
创建一个输入字段并为此输入字段定义一个名称。
并通过
this.refs.inputFieldName.value从此输入字段中收集数据
和
将其推送到声明的数组变量中。
Git Project下方的链接包含完整的文档和文档。
尝试
答案 1 :(得分:0)
您可以将点击房间的index
传递给onSelectRooms
功能。
export default class ExportReportRoomSelectionModal extends React.Component {
constructor(props) {
super(props);
const roomOrder = configContext.value.roomOrder;
this.state = {
rooms: roomOrder,
selectedRooms: [],
};
}
onSelectRooms = (e, index) => {
this.setState(prevState => ({
selectedRooms: [...prevState.selectedRooms, index]
}));
}
render() {
return (
<Modal>
<Modal.Header>
<Modal.Title>Title</Modal.Title>
</Modal.Header>
<Modal.Body>
<p>Number of rooms: {this.state.rooms.length}</p>
<p>Rooms:</p>
<Grid fluid={true}>
<Row className="show-grid">
{ this.state.rooms.map((name, i ) =>
<Col key={i}>
<Panel onClick={() => this.onSelectRooms(i)}>
<Panel.Heading id={name}>
{name}
</Panel.Heading>
</Panel>
</Col>
)}
</Row>
</Grid>
</Modal.Body>
</Modal>);
}
}
答案 2 :(得分:0)
您可以尝试一下,
const joined = this.state.selectedRooms.concat(newItem);
this.setState({ selectedRooms: joined })
答案 3 :(得分:0)
使用以下代码更改onSelectRooms()并检查
onSelectRooms = (e) => {
const newItem = e.target.id;
let roomArray = this.state.selectedRooms;
roomArray.push(newItem); //add value in local array
this.setState({selectedRooms: roomArray}); //replace selectedRooms with local arry
}
享受!