ReactJS:如何从表单输入值中添加新行到表中?

zed5wv10  于 2022-12-29  发布在  React
关注(0)|答案(3)|浏览(130)

我在学ReactJS
我想在输入字段中添加文本,然后单击“提交”按钮。这个新值将添加到表中。
我从一个简单的表单组件开始,它有名字和姓氏输入值。一个扩展表单的表组件。表单添加到默认的App类。
Form.js

import React, { Component } from 'react';
import './form.css';

export default class Form extends Component {

  render(){
      return(
        <div id="Form">

          <form onSubmit={this.handleSubmit}>
              Username<br/>
              <input type="text" name="username" placeholder="Username" /><br/>
              Password<br/>
              <input type="password" name="password" placeholder="Password"/><br/>
              <br/>
              <input type="submit" value="Submit" />
          </form>
        </div>
      );
    }

}

Table.js

import React, { Component } from 'react';
import './table.css';
import Form from './Form.js';

export default class Table extends Form {
  render(){
      return(
        <div id="Table">
          <table>
            <tr>
              <th>Username</th>
              <th>Password</th>
            </tr>
            <tr>
              <td>a</td>
              <td></td>
            </tr>

          </table>
        </div>
      );
    }

}

App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import Table from './Table.js';
import Form from './Form.js';
import './App.css';

class App extends Component {
  render() {
    return (
      <div className="App">
        <Form />
      </div>
    );
  }
}

export default App;
brc7rcf0

brc7rcf01#

我做了一个CodePen with a working example.

    • 说明**

您必须在您的父组件上编写方法,并将它们作为 prop 传递给您的子组件。您的应用程序的状态也将在父组件上。
您应该创建的方法是handleInputChange和handleFormSubmit。您必须将这两个方法作为属性传递给表单组件。
状态将包含新项的"用户名"和"密码",以及现有项的数组和新项将添加到的位置。您将把项的数组作为属性传递给Table组件。
在Table组件中,只需Map项目prop,并使用数组中每个项目的数据打印<tr>
./App.js

import React, { Component } from 'react';
import './App.css';
import Table from './Table';
import Form from './Form';

class App extends Component {
  constructor() {
    super();

    this.state = {
      username: '',
      password: '',
      items: []
    }
  };

  handleFormSubmit = (e) => {
    e.preventDefault();

    let items = [...this.state.items];

    items.push({
      username: this.state.username,
      password: this.state.password
    });

    this.setState({
      items,
      username: '',
      password: ''
    });
  };

  handleInputChange = (e) => {
    let input = e.target;
    let name = e.target.name;
    let value = input.value;

    this.setState({
      [name]: value
    })
  };

  render() {
    return (
      <div className="App">
        <Table items={ this.state.items }/>
        <Form handleFormSubmit={ this.handleFormSubmit } 
          handleInputChange={ this.handleInputChange }
          newUsername={ this.state.username }
          newPassword={ this.state.password } />
      </div>
    );
  }
}

export default App;

./Form.js

import React, { Component } from 'react';

class Form extends React.Component {
  render() {
    return (
      <div id="Form">
        <h3>Add a new item to the table:</h3>  
        <form onSubmit={this.props.handleFormSubmit}>
          <label htmlFor="username">
          Username:
          <input id="username" value={this.props.newUsername} 
            type="text" name="username"
            onChange={this.props.handleInputChange} />
          </label>
          <label for="password">
          Password:
          <input id="password" value={this.props.newPassword} 
            type="password" name="password"
            onChange={this.props.handleInputChange} />
          </label>
          <button type="submit" value="Submit">Add Item</button>
        </form>
      </div>
    );
  }
}

export default Form;

./Table.js

import React, { Component } from 'react';

class Table extends React.Component {
  render() {
    const items = this.props.items;
    return (
      <div id="Table">
        <table>
          <tbody>
            <tr>
              <th>Username</th>
              <th>Password</th>
            </tr>
            {items.map(item => {
              return (
                <tr>
                  <td>{item.username}</td>
                  <td>{item.password}</td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    );
  }
}

export default Table;

我建议您阅读React文档的"受控组件"部分。
对于更复杂的表单,可以使用Reduxredux-form
我希望这会有所帮助。

j5fpnvbx

j5fpnvbx2#

你可以像下面这样做。存储你的输入字段值到一个数组状态,并把它传递给你的表组件作为 prop 。在你的表组件中,取一个数组变量,迭代你的formData prop ,然后把用户名和密码推到行数组中,并打印出来。
您可以在下面查看全部功能
Form.js

import React, { Component } from 'react';
import './form.css';
import Table './Table.js';

export default class Form extends Component {
    constructor(props){
    super(props);
    this.state = {
    uName: '',
    uPassword: '',
    formValid: false,
    formData: []
}
    this.changeUsername = this.changeUsername.bind(this);
    this.changePassword = this.changePassword.bind(this);
}

changeUsername(event){
   this.setState({
      uName: event.target.value
   })
}

changePassword(event){
    this.setState({
      uPassword: event.target.value
    })
}

handleSubmit(e){
     e.preventDefault();
     if(this.state.uName != "" && this.state.uPassword != "" && this.state.uName != null && this.state.uPassword != null){
         let object = {}
         object.username = this.state.uName;
         object.password = this.state.uPassword;

         this.setState({
            formValid: true,
            formData: obj
          })

     }
}

renderTable(){
     <Table formData = {this.state.formData} />
}

  render(){
      return(
        <div id="Form">

          <form onSubmit={this.handleSubmit}>
              Username<br/>
              <input type="text" value = {this.state.uName} name="username" placeholder="Username" onChange={this.changeUsername}/><br/>
              Password<br/>
              <input type="password" value = {this.state.uPassword} name="password" placeholder="Password" onChange={this.changePassword}/><br/>
              <br/>
              <input type="submit" value="Submit" />
          </form>
{this.state.formValid ? this.renderTable() : ''}
        </div>
      );
    }

}

Table.js

import React, { Component } from 'react';
import './table.css';

export default class Table extends Form {
constructor(props){
    super(props);

}
  render(){
     const {formData} = this.props;
     let rows = []
     if(formData){
       for(var i=0; i<formData.length;i++){
        rows.push(<tr><td>{formData[i].username}</td><td>{formData[i].password}</td></tr>)
        }  
      }
      return(
        <div id="Table">
          <table>
            <tr>
              <th>Username</th>
              <th>Password</th>
            </tr>
            {rows}

          </table>
        </div>
      );
    }
   }
w8f9ii69

w8f9ii693#

handSubmit =(e)=> {
  for(let i=0; e.target.length-1>=i; i++){
     console.log(e.target[i].value)
  }
  e.preventDefault()
}

相关问题