0

我有一个动态生成表单字段的表单。现在的问题是非动态生成的字段正在获取输入,而动态生成的字段未在字段中获取输入。 name='name' 并且name='age' 字段没有得到输入我无法在其中插入数据。而前两个字段所有者和描述工作正常

import React from "react";
class Form extends React.Component {

  state = {
    cats: [{ name: "", age: "" }],
    owner: "",
    description: ""
  };
  handleChange = e => {
    alert('inot');
    if (["name", "age"].includes(e.target.className)) {
      let cats = [...this.state.cats];
      cats[e.target.dataset.id][
        e.target.className
      ] = e.target.value.toUpperCase();
      this.setState({ cats }, () => console.log(this.state.cats));
    } else {
      this.setState({ [e.target.name]: e.target.value.toUpperCase() });
    }
  };
  addCat = e => {
    this.setState(prevState => ({
      cats: [...prevState.cats, { name: "", age: "" }]
    }));
  };
  handleSubmit = e => {
    e.preventDefault();
  };
  handleClick = e => document.getElementById(e.target.id).remove();

  // changeOption =(e) => {
  //   this.setState.cats(e.target.value);
  // }


  render() {
    let { owner, description, cats } = this.state;
    return (
      <form onSubmit={this.handleSubmit} onChange={this.handleChange}>
        <div className='row mt-5'>
          <div className='col-md-12 mb-5'>
            <h3 className='text-center text-primary'>Create Products Option</h3>
          </div>
          <div className='col-md-3'></div>
          <div className='col-md-3'>
            <label htmlFor='name'>
              <b>Owner</b>
            </label>
            <input
              type='text'
              className='form-control'
              name='owner'
              id='owner'
              value={owner}
            />
          </div>
          <div className='col-md-3'>
            <label htmlFor='description'>
              <b>Description</b>
            </label>
            <input
              type='text'
              className='form-control'
              name='description'
              id='description'
              value={description}
            />
            <button
              className='btn btn-success rounded-0 w-25 float-right mt-2 shadow-none'
              onClick={this.addCat}
            >
              +
            </button>
          </div>
          <div className='col-md-3'></div>
        </div>

        {cats.map((val, idx) => {
          let catId = `cat-${idx}`,
            ageId = `age-${idx}`;
          return (
            <form onSubmit={this.handleSubmit} onChange={this.handleChange}>
            <div id={ageId} key={idx}>
              <div className='row mt-5'>
                <div className='col-md-3'></div>
                <div className='col-md-3'>
                  <label htmlFor={catId}>
                    <b>{`Cat #${idx + 1}`}</b>
                  </label>
                  <input
                    type='text'
                    name='name'
                    data-id={idx}
                    id={catId}
                    value={cats[idx].name}
                    className='name form-control'
                  />


                </div>
                <div className='col-md-3'>
                  <label htmlFor={ageId}>
                    <b>Age</b>
                  </label>
                  <input
                    type='text'
                    name='age'
                    data-id={idx}
                    id={ageId}
                    value={cats[idx].age}
                    className='age form-control'
                  />
                  <button
                    className='btn btn-success rounded-0 w-25 float-right mt-2 shadow-none'
                    onClick={this.addCat}
                  >
                    +
                  </button>
                  <input
                    type='button'
                    name={ageId}
                    data-id={idx}
                    id={ageId}
                    value={"-"}
                    className='age float-right mt-2 mr-3 btn btn-danger w-25 rounded-0 w-25 shadow-none'
                    onClick={this.handleClick}
                  />

                </div>
                <div className='col-md-3'></div>
              </div>

            </div>
            </form>
          );
        })}
        <div className='row mt-3'>
          <div className='col-md-3'></div>
          <div className='col-md-3'>
            <label htmlFor='name'>
              <b>Min Selection</b>
            </label>
            <input
              type='text'
              className='form-control'
              name='min'
              id='min'
              value={""}
            />
          </div>
          <div className='col-md-3'>
            <label htmlFor='description'>
              <b>Max Selection</b>
            </label>
            <input
              type='text'
              className='form-control'
              name='max'
              id='max'
              value={""}
            />
            <input
              className='float-right btn btn-success mt-3'
              type='submit'
              value='Submit'
            />
            {/* <button className="float-right" onClick={this.addCat}>Add new cat</button> */}
          </div>
          <div className='col-md-3'></div>
        </div>
      </form>
    );
  }
}
export default Form;
4

1 回答 1

1

Codesandbox 在这里。看起来您应该在控制台中看到一些错误,这些错误可能会提供一些解释:

Warning: Failed prop type: You provided a `value` prop to a form field without an `onChange` handler. This will render a read-only field. If the field should be mutable use `defaultValue`. Otherwise, set either `onChange` or `readOnly`.

详细解答

工作沙箱在这里。这里有一些问题:

你的handleChange功能需要改变

您的功能正在查看className哪个不起作用。例如,您的输入返回form-control name。而是尝试使用元素的name.

更新功能:

  handleChange = e => {
    if (["name", "age"].includes(e.target.name)) {
      let cats = [...this.state.cats];
      cats[e.target.dataset.id][e.target.name] = e.target.value.toUpperCase();
      this.setState({ cats }, () => console.log(this.state.cats));
    } else {
      this.setState({ [e.target.name]: e.target.value.toUpperCase() });
    }
  };

在旁边

不要<form>在其他元素中渲染<form>元素。 不要这样做。您在这里不需要其他表格。只需删除它。

// Line 76-80:
        {cats.map((val, idx) => {
          let catId = `cat-${idx}`,
            ageId = `age-${idx}`;
          return (
            <form onSubmit={this.handleSubmit} onChange={this.handleChange}>
// ...

于 2019-11-17T21:51:14.337 回答