2016-07-16 20 views
1

私はReactでwebpackを使用しています。このビルドで何が起こっているのか理解できません。これが起こっているはずのことです。React Webpack - フォーム送信時に入力値を取得しないSubmitボタン

  1. VAR headerInput変更がどのような値のonChangeを入力されています。

  2. フォームが送信される(をonSubmit)にconsole.logはheaderInput値を記録します。

問題:.0.0.1:コンソールが記録されます値は、数値で、それは通常のようなものです。私はそれがconsole.logのclickイベントだと思う。なぜ、値がhandlerInput関数のように割り当てられていないのですか?

ご迷惑をおかけして申し訳ありません。ありがとう、すべて。

var headerInput = null; 

import React from "react"; 

export default class Navigation extends React.Component{ 
    handlerInput(e,headerInput){ 
    headerInput = e.target.value; 
    console.log(headerInput); 
    }; 
    clickSubmit(e,headerInput){ 
    e.preventDefault(); 
    console.log(headerInput); 
    }; 
    render(){ 
    return(
    <form onSubmit={this.clickSubmit.bind(this)}> 
     <input type="text" placeholder="change header" onChange={this.handlerInput.bind(this)} /> 
     <button>Change Header</button> 
    </form> 
    ); 
    } 
}; 

答えて

1

これはReactを使用するための推奨方法ではありません。あなたの状態を格納するために「グローバル」に頼る代わりに、コンポーネントに付属の状態APIを使用する必要があります。そのよう

は:

import React from "react"; 

export default class Navigation extends React.Component{ 
    constructor(props) { 
    super(props); 

    // Set up your default state here. 
    this.state = { }; 

    // Do early binding. 
    this.handlerInput = this.handlerInput.bind(this); 
    this.clickSubmit = this.clickSubmit.bind(this); 
    } 

    handlerInput(e){ 
    // Use setState to update the state. 
    this.setState({ 
     headerInput: e.target.value 
    } 
    }; 
    clickSubmit(e){ 
    e.preventDefault(); 

    // You read state via this.state 
    console.log(this.state.headerInput); 
    }; 
    render(){ 
    return(
    <form onSubmit={this.clickSubmit}> 
     /* Make sure you pass the current state to the input */ 
     <input 
     type="text" 
     placeholder="change header" 
     onChange={this.handlerInput} 
     value={this.state.headerInput} 
     /> 
     <button>Change Header</button> 
    </form> 
    ); 
    } 
}; 

私は間違いなくあなたが公式の再訪をお勧めしますthinking in reactreact formsチュートリアルのように、ドキュメントを反応させます。

+0

私はテスト目的のために、このインスタンス内のグローバル変数を使用していました。 私は全体的に州を少なくし、変数を割り当てないで入力値を取得する方が好きです。私は参考文献について学んだ。私はこの問題を解決するためにrefsを使用して終了しました。 https://jsfiddle.net/u46Lj95r/ –

1

入力は厳密に一方通行である場合には(あなただけそれから読んで)、文字列、参考文献は廃止されていないが、その後、ちょうど彼らが、...

REF

import React from "react"; 

class Navigation extends React.Component{ 
    clickSubmit(e,headerInput){ 
    e.preventDefault(); 
    console.log(this.inputEl.value); 
    }; 
    render(){ 
    return(
     <form onSubmit={this.clickSubmit.bind(this)}> 
     <input placeholder="change header" ref={el => this.inputEl = el} /> 
     <button>Change Header</button> 
     </form> 
    ); 
    } 
}; 

注意を使用従来のものとみなされます( )。将来的には廃止される可能性があります。コールバック の参照が優先されます。

https://facebook.github.io/react/docs/more-about-refs.html

関連する問題