2016-11-09 57 views
0

因此,我在使用create-react-app的第一个React应用程序中尝试了一下,我试图根据this GitHub项目制作一个多阶段表单。特别是AccountFieldsRegistration部件。正确的方式来更新React中的表单状态?

该项目似乎在更旧版本反应过来被写入,所以我不得不尝试和更新 - 这是我到目前为止有:

App.js:

import React, { Component } from 'react'; 
import './App.css'; 
import Activity from './Activity'; 

var stage1Values = { 
    activity_name : "test" 
}; 

class App extends Component { 
    constructor(props) { 
     super(props); 

     this.state = { 
      step: 1 
     }; 
    }; 

    render() { 
     switch (this.state) { 
      case 1: 
       return <Activity fieldValues={stage1Values} />; 
     } 
    }; 

    saveStage1Values(activity_name) { 
     stage1Values.activity_name = activity_name; 
    }; 

    nextStep() { 
     this.setState({ 
      step : this.state.step + 1 
     }) 
    }; 
} 

export default App; 

Activity.js:

import React, { Component } from 'react'; 

class Activity extends Component { 
    render() { 
     return (
      <div className="App"> 
       <div> 
        <label>Activity Name</label> 
        <input type="text" ref="activity_name" defaultValue={this.props.stage1Values} /> 
        <button onClick={this.nextStep}>Save &amp; Continue</button> 
       </div> 
      </div> 
     ); 
    }; 

    nextStep(event) { 
     event.preventDefault(); 

     // Get values via this.refs 
     this.props.saveStage1Values(this.refs.activity_name.getDOMNode().value); 
     this.props.nextStep(); 
    } 
} 

export default Activity; 

我已经看了一些例子,这似乎是存储当前状态的正确方法(允许用户来回走不同部分之间Ø f表格),然后存储这个阶段的值。当我点击Save & Continue按钮时,出现错误Cannot read property 'props' of null。我的意思是显然这意味着this为空,但我不确定如何解决它。

我接近这个错误的方式吗?我发现的每个例子似乎都有一个完全不同的实现。我来自基于Apache的背景,所以这种方法在一般情况下我觉得很不寻常!

+1

尝试'this.nextProps。绑定(这)'。详细http://egorsmirnov.me/2015/08/16/react-and-es6-part3.html – Siou

+0

@Siou你建议在'App.js'的构造函数中做这个? – user3420034

+0

''in'Activity.js' – TomIsion

回答

0

在这NEXTSTEP没有指向活动,只是做这样

<button onClick={()=>this.nextStep()}>Save &amp; Continue</button> 
0

绑定NEXTSTEP功能:

<button onClick={this.nextStep.bind(this)}>Save &amp; Continue</button> 

或者在构造函数中:

constructor(props){ 
    super(props); 
    this.nextSteps = this.nextSteps.bind(this); 
}