2016-11-09 105 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); 
}