【问题标题】:React add new item to a table反应将新项目添加到表中
【发布时间】:2020-10-18 16:47:48
【问题描述】:

我正在做一个 React 项目。我需要使用表单将新数据添加到表中。在这里,当我运行“npm start”命令时,它会在列表中显示“Audi”。但是当我尝试添加新的车辆品牌时,它不会添加。没有错误显示。谁能解决这个问题。

这是我的 vehicleType.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;

【问题讨论】:

    标签: reactjs forms jsx


    【解决方案1】:

    试试这个

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

    【讨论】:

      【解决方案2】:

      我认为他们提供的 ref 上的 reactstrap 存在一些问题,这是满足您要求的工作沙箱 sandbox

      如果您仍然需要使用 reactstrap,那么您需要使用状态变量,例如

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

      在handleChange中添加这个

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

      【讨论】:

        猜你喜欢
        • 2013-05-30
        • 2022-12-03
        • 1970-01-01
        • 2019-06-06
        • 2021-07-01
        • 2021-07-30
        • 2017-08-12
        • 1970-01-01
        • 2011-10-18
        相关资源
        最近更新 更多