2016-11-09 35 views
0

create-react-appを使って私の最初のReactアプリに行って、this GitHubプロジェクトに基づいて多段階フォームを作ろうとしています。特に、およびRegistration部分。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; 

私は多くの例を見てきましたが、これは(ユーザーが異なる部分の間を行き来できるようにするために、現在の状態を保存するための適切なアプローチであると思われますo f)を入力し、この段階から値を保存します。 Save & Continueボタンをクリックすると、Cannot read property 'props' of nullというエラーが表示されます。明らかにこれはthisがヌルであることを意味しますが、私はそれを修正する方法がわかりません。

私はこれに間違った方法で近づいていますか?私が見つけたすべての例は、まったく異なる実装を持つようです。私はApacheベースの背景から来ているので、このアプローチは一般的に私は非常に珍しいと思う!

+1

try this.nextProps。バインド(これ) '。詳細については、http://egorsmirnov.me/2015/08/16/react-and-es6-part3.html – Siou

+0

@ Siouあなたは 'App.js'のコンストラクタ内でこれを行うことをお勧めしますか? – user3420034

+0

'' 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); 
} 
関連する問題