反应形式发送空对象

时间:2019-05-27 21:40:34

标签: javascript arrays reactjs

我正在尝试将表单组件中的用户输入发送到管理状态的组件。我尝试使用回调,但是我的输入没有被发送。

试图在回调中使用表单对象

//here is the form component

class ListForm extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      NewItem: {
        itemText: "",
        id: Date.now(),
        completed: false
      }
    };
  }

  handleChanges = e => {
    this.setState({...this.state,
      NewItem: { ...this.state.NewItem, [e.target.name]: e.target.value }
    });
  };

  submitItem = e => {
     this.setState({ itemText: "" });
    this.props.addItem(e, this.state.NewItem);

  };

  render() {
    return (
      <form onSubmit={this.submitItem}>
        <input
          type="text"
          value={this.state.NewItem.itemText}
          name="itemText"
          onChange={this.handleChanges}
        />
        <button>Add</button>
      </form>
    );
  }
}

export default ListForm;
addItem is in the parent component and looks like this. Groceries is just an array of objects with itemText, id and completed 

addItem = (e, item) => {
    e.preventDefault();
        this.setState({
      ...this.state,
      groceries: [...this.state.groceries, item]
    });
  };

我可以输入表格,但是当我按Enter键时,列表中什么都没有添加

1 个答案:

答案 0 :(得分:0)

首先要尝试的是将e.persist添加到您的addItem()函数中

addItem = (e, item) => {
    e.preventDefault();
    e.persist()
        this.setState({
      ...this.state,
      groceries: [...this.state.groceries, item]
    });
  };

另一个选项是使用redux将表单数据保存为Global状态,然后通过redux在父组件中访问它。这是一个可能看起来像的例子:

import React, { Component } from 'react';
import * as ACTIONS from '../store/actions/actions';
import { connect } from 'react-redux';



class Form1 extends Component {

  state ={
    value: ''
  }

  handleChange = (event) => (
    this.setState({value: event.target.value})
  )

  handleSubmit = (event) => {
    event.preventDefault()
    this.props.input_action_creator(event.target.name.value)
  }

  render() {
    return (
      <div>
        <form onSubmit={this.handleSubmit}>
          <input id="name" onChange={this.handleChange} type="text" />
          <button type="submit"> Submit </button>
        </form>
        <br />
      </div>
    )}
}




function mapDispatchToProps(dispatch) {
  return {
    input_action_creator: (text) => dispatch(ACTIONS.user_input(text))
  }
}


export default connect(mapDispatchToProps)(Form1);


class Parent extends Component {

  access form data with 

  this.props.user_Text

}

function mapStateToProps(state) {
  return {
    user_text: state.user_reducer.user_text
  }
}

如果您有兴趣,这是一个功能齐全的react-redux项目

https://github.com/iqbal125/modern-react-app-sample