React组件,为什么在表单提交时未定义一半你的道具?

时间:2017-01-08 05:55:05

标签: javascript forms reactjs ecmascript-6 undefined

React的新手,希望这不是非常明显的事情。我一直在墙上撞了一会儿。

根据Chrome中的React Dev Tools,定义了所有表单的道具以及我期望它们。即使提交表单。大。

不幸的是,在handleSubmit()中,只有2个可见: id 名称都是未定义,尽管在​​Dev Tools中显示正确的值。

为什么世界上有一半(只有一半)道具显示为 undefined

  import React, {Component} from 'react';
  import {
  TextField,
  IconButton,
  FlatButton,
  DatePicker,
  Snackbar,
  RaisedButton,
  LinearProgress,
  Dialog,
  DropDownMenu,
  MenuItem,
  AppBar
} from 'material-ui';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import EditAttachFile from 'material-ui/svg-icons/editor/attach-file.js';
import NotificationSync from 'material-ui/svg-icons/notification/sync.js';
import EventNote from 'material-ui/svg-icons/notification/event-note.js';

class NameFirstForm extends Component {
  constructor(props) {
    super(props);
    this.state = {value: props.person.getAttr('nameFirst')};


    this.handleChange = this.handleChange.bind(this);
    this.handleSubmit = this.handleSubmit.bind(this);
  }

  componentWillReceiveProps(nextProps) {
    this.setState({value: nextProps.person.getAttr('nameFirst')});
  }

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

  handleSubmit(event) {
    console.log("value", event.target.value);
    event.preventDefault();
    this.props.save.call(this.props.ctx, event);
  }

  render() {
    return (
      <div>
      <form 
        onSubmit={this.handleSubmit}
        name="nameFirst"
        id={this.props.person.getAttr('id')}
        person={this.props.person}
        value={this.state.value} 
      >
        <MuiThemeProvider>
          <TextField 
            name="nameFirst"
            id={this.props.person.getAttr('id')}
            person={this.props.person}
            value={this.state.value} 
            underlineStyle={ {color: 'rgb(0,188,212)' } }  
            floatingLabelFixed={true} 
            floatingLabelText="First Name" 
            onChange={this.handleChange}
          />
        </MuiThemeProvider>
      </form>
        </div>
    );
  }
}

export default NameFirstForm;

1 个答案:

答案 0 :(得分:2)

您的问题是从表单中读取值。我看到的是你可以用你的状态和你的属性返回具有正确值的对象,如下所示:

handleSubmit(event) {
    event.preventDefault();
    this.props.save.call(this.props.ctx, {
      person: this.props.person,
      id: this.props.person.getAttr('id'), //You could skip this if you already have the person object
      newValue: this.state.value
    });
}