React 表单,提交对象,然后将其推送到数组

React form, to submit object which is then pushed to array

我是 React 新手,不确定如何操作。

我有一组对象,我已经映射并呈现在我的视图中。我想做的是设置一个表单,将每个字段的值提交给新对象的相应属性,但我不确定如何去做。

这是我在视图中呈现的初始数据:

contactArray = [
  {
    name: 'John'
    email: 'john@email.com'
    number: 111-111-111
  },
  {
    name: 'Dave'
    email: 'dave@email.com'
    phone: '222-222-222'
  }
]

那么我有一个表格:

class InputForm extends Component {
  render() {
    return (   
        <form>
          <input type='text' onChange={this.handleChange}/>
          <input type='text' onChange={this.handleChange}/>
          <input type='text' onChange={this.handleChange}/>
          <button type='submit' onSubmit={this.handleSubmit}>SUBMIT</button>
        </form>
    ) 
  }

然后我假设我将状态声明为:

constructor(props) {
  super(props);
  this.state = {
    name: '',
    email: '',
    phone: ''
  }
}

然后提交功能我真的不知道怎么处理...

handleSubmit() {
  // not sure about this...
  this.setState({
    name: // ????
    email: // ????
    phone: // ????
  })
}

然后我想清除提交表单,以及用于推送新对象的对象,它现在在数组中(我希望这是有道理的...)

所以,我什至不确定如何在这种情况下使用状态,但最终我想 push() 将新对象 push() 渲染到数组中,其中包含完成时的所有属性表格。

抱歉,到目前为止我的工作还不能更完整,但至少会感谢一些关于此的指示!

您不需要为所有 inputs 设置 state。如果你这样做,当你有更多 input 字段时,这将是一个问题。请参阅下面的 fiddle,其中,我使用单个 state 来存储整个联系人。当您按下提交按钮时,它会从 input 中获取所有值并将其保存到 state。希望对您有所帮助!

Fiddle: http://jsfiddle.net/Pranesh456/8u4uz5xj/1/

[更新]

  1. e.value = null 将清除表单中的值。这样,您就可以重置整个表格。
  2. slice()用于复制状态中的数组。由于数组的赋值是对原数组的reference,对新数组的任何操作也会反映在原数组中。

示例:

a = [1,2,4]
b = a
b.push(7)
console.log(b) //prints [1,2,4,7]
console.log(a) //also prints [1,2,4,7]

但是

b = a.slice() //creates a copy of a
b.push(7)
console.log(b) //prints [1,2,4,7]
console.log(a) //also prints [1,2,4]

有关 slice

的更多详细信息

这样做不会改变现有状态,这是一个很好的做法。

希望对您有所帮助!!

据我了解,您想将新人推向现有 contactArray?我将分享我的做法。看看:

const contactArray = [
{
    name: 'John',
    email: 'john@email.com',
    phone: '111-111-111'
  },
  {
    name: 'Dave',
    email: 'dave@email.com',
    phone: '222-222-222'
  }
];

class Form extends React.Component {

  constructor() {
    super();
    this.state = {
      contacts: contactArray
    };
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  handleSubmit(e) {
    e.preventDefault();
    const
    { contacts } = this.state,
    name = this.refs.name.value,
    email = this.refs.email.value,
    phone = this.refs.phone.value;
    this.setState({
      contacts: [...contacts, {
        name,
        email,
        phone
      }]
    }, () => {
      this.refs.name.value = '';
      this.refs.email.value = '';
      this.refs.phone.value = '';
    });
  }

  render() {
    const { contacts } = this.state;
    console.log('message',this.state.contacts);
    return (   
      <div>
        <h2>Add Someone</h2>
        <form onSubmit={this.handleSubmit}>
          <input type="text" ref="name" placeholder="name" />
          <input type="text" ref="email" placeholder="email" />
          <input type="text" ref="phone" placeholder="phone" />
          <button type="submit">Submit</button>
        </form>
        <h2>Exsiting contacts:</h2>
        <ul>
          {contacts.map((contact) => 
           <li>{`Name: ${contact.name} Email: ${contact.email} Phone: ${contact.phone}`}</li>
          )}
        </ul>
      </div>
    ) 
  }
}

ReactDOM.render(<Form />, document.getElementById('root'));

所以我们做的第一件事就是将 contactArray 保存在我们要使用它的实际组件中,接下来我们贴花并绑定我们的 handleSubmit 我正在使用 refs输入以获得他们的价值。 this.setState ({ contacts: [...contacts] , { Object }); 这里我们使用 ES6 扩展运算符将所有现有联系人传递到我们的新状态并添加新联系人。 { name, email, phone } 和做 { name:name, email:email ...} 完全一样,只是一个简写, this.setState({}, () => { Callback! });this.setState({}); 的回调函数中,我将清除输入值。现场演示:http://codepen.io/ilanus/pen/qaXNmb

这是您可以使用的另一种方法,相同的结果不同的方法。

const contactArray = [
  {
    name: 'John',
    email: 'john@email.com',
    phone: '111-111-111'
  },
  {
    name: 'Dave',
    email: 'dave@email.com',
    phone: '222-222-222'
  }
];

class Form extends React.Component {

  constructor() {
    super();
    this.state = {
      contacts: contactArray,
      newContact: {
       name: '',
       email: '',
       phone: ''
     }
    };
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleInput = this.handleInput.bind(this);
  }

  handleSubmit(e) {
    e.preventDefault();
    const { contacts, newContact } = this.state;
    this.setState({
      contacts: [...contacts, newContact],
    }, () => {
      for (let val in newContact) {
        newContact[val] = ''; // Clear the values...
      }
      this.setState({ newContact });
    });
  }

  handleInput(e, element) {
    const { newContact } = this.state;
    newContact[element] = e.target.value;
    this.setState({ newContact });
  }

  render() {
    const { contacts, newContact } = this.state;
    const { name, email, phone } = newContact;
    return (   
      <div>
        <h2>Add Someone</h2>
        <form onSubmit={this.handleSubmit}>
          <input type="text" value={name} onChange={e => this.handleInput(e, 'name')} placeholder="name" />
          <input type="text" value={email} onChange={e => this.handleInput(e, 'email')} placeholder="email" />
          <input type="text" value={phone} onChange={e => this.handleInput(e, 'phone')} placeholder="phone" />
          <button type="submit">Submit</button>
        </form>
        <h2>Exsiting contacts:</h2>
        <ul>
          {contacts.map((contact) => 
           <li>{`Name: ${contact.name} Email: ${contact.email} Phone: ${contact.phone}`}</li>
          )}
        </ul>
      </div>
    ) 
  }
}

ReactDOM.render(<Form />, document.getElementById('root'));

现场演示:http://codepen.io/ilanus/pen/LRjkgx

我强烈推荐使用第一个示例。因为它的性能会更好:)