weixin_33722405 2016-08-29 09:13 采纳率: 0%
浏览 88

ReactJS表单渲染问题

I'm learning reactjs and I have problem with my form.

I'm getting error from my console like this profile.js:54 Uncaught TypeError: Cannot read property 'target' of undefined when I reload my page. Form is not rendering in my page, but I think this code should work.

my file profile.js:

var BasicInput = React.createClass({
    render: function () {
        return (
            <input type="text" onChange={this.props.valChange} value={ this.props.val} />
        );
    }
});

var BasicForm = React.createClass({
    getInitialState: function(){
      return {
          firstName: '',
          lastName: ''
      };
    },

    submit: function (e){
      var self;

      e.preventDefault()
      self = this;

      console.log(this.state);

      var data = {
        firstName: this.state.firstName,
        lastName: this.state.lastName
      };

      // Submit form via jQuery/AJAX
      $.ajax({
        type: 'POST',
        url: '/accounts/profile/details-form',
        data: data
      })
      .done(function(data) {
        self.clearForm()
      })
      .fail(function(jqXhr) {
        console.log('failed to change basic info');
      });

    },

    clearForm: function() {
      this.setState({
        firstName: "",
        lastName: ""
      });
    },

    firstnameChange: function(e){
      this.setState({firstName: e.target.value});
    },

    lastnameChange: function(e){
     this.setState({lastName: e.target.value});
    },

    render: function() {
        return (
            <form onSubmit={this.submit}>
                <div className="form-half">
                    <BasicInput label="Firstname" valChange={this.firstnameChange()} val={this.state.firstName}/>
                </div>
                <div className="form-half">
                    <BasicInput label="Lastname" valChange={this.lastnameChange()} val={this.state.lastName}/>
                </div>
                 <button type="submit">Submit</button>
            </form>
        );
    }
});


ReactDOM.render(
    <BasicForm />,
    document.getElementById('basicInfoForm')
  );

What is wrong in this code?

Many thanks for help with this problem.

  • 写回答

1条回答 默认 最新

  • weixin_33696822 2016-08-29 09:16
    关注

    You should pass reference to functions firstnameChange and lastnameChange but not call them (remove () from each of them)

    <BasicInput 
      label="Firstname" 
      valChange={ this.firstnameChange } 
      val={ this.state.firstName }
    />
    
    <BasicInput 
      label="Lastname" 
      valChange={ this.lastnameChange } 
      val={ this.state.lastName }
    />
    

    Example

    评论

报告相同问题?

悬赏问题

  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突