React 将新项添加到表中



我正在做一个React项目。我需要使用表单向表中添加新数据。在这里,当我运行"npm start"命令时,它将在列表中显示"奥迪"。但是当我尝试添加新的汽车品牌时,它不会添加。没有显示任何错误。任何人都可以解决这个问题。

这是我的车辆类型.jsx 文件

import React, { Component } from "react";
import { Button } from "reactstrap";
import {FormGroup,Form,Input,Col} from "reactstrap";
class VehicleType extends Component {
constructor(props){
super(props);
this.state = {
items : ['Audi']
}

}


addItem(e){
e.preventDefault();
const {items} =this.state;
const newItem = this.newItem.value;

this.setState({
items : [...this.state.items,newItem]
})

}

render() {
const { items } = this.state;
return ( 
<>

<Form onSubmit={(e) => {this.addItem(e)}}>
<Row>
<Col md="3">
<FormGroup className="has-success">
<Input ref={(input) => this.newItem =input } className="is-valid" placeholder="Add" type="text"/>
</FormGroup>
</Col>
<Col md="4">
<Button color="primary" size="lg" type="submit" >
Add new vehicle brand
</Button>
</Col>
</Row>
</Form>


<Table className="align-items-center" responsive>

<tbody>
{
items.map(item => {
return(
<tr key = {item}>
<th scope="row" col-md-2>
<span className="mb-0 text-sm">
{item}
</span>
</th>
</tr>
)}
}
</tbody>
</Table>

</>
);
}
}
export default VehicleType;

我认为他们提供的参考上的反应库存在一些问题,这里是满足您要求的工作沙箱 沙盒

如果你仍然需要使用Reactstrap,那么你需要使用状态变量,如

<Input onChange={handleInputChange} value={this.state.addValue} className="is-valid" placeholder="Add" type="text"/>

在句柄中更改添加此

handleInputChange(e){
this.setState({addValue:e.target.value})
}

试试这个

addItem(e){
e.preventDefault();
const {items} =this.state;
items.push(this.newItem.value) 
this.setState({ items })  
}

最新更新