2016-05-21 6 views
0

達成しようとしていること:データを子から親に渡す。反応状態が不一致

私はそれを達成しようとしている方法

this.stateを使用してhere

どの単語タイトルのわからない説明した:I私は状態を変更する機能でconsole.log(this.state)this.stateで正しい値を印刷されます。しかし、別の関数で状態を読み取ろうとすると、this.stateは明らかにまだ空の値になっています。

constructor(props) { 
    super(props); 
    this.state = { 
     titleInputValue: "", 
    }; 
} 

<form onSubmit={this.handleSubmit.bind(this)}> 
    <TextInput 
     val={this.state.titleInputValue} 
     changeHandler={this.textInputChangeHandler} /> 
</form> 


// This is the function which can apparently only get the initial state 
// title and body are empty strings, they should have values 
handleSubmit(event) { 
    event.preventDefault(); 
    const title = this.state.titleInputValue; 
    const body = this.state.bodyInputValue; 
    console.log(this.state); 
    Meteor.call('stories.insert',title,body); 
} 

// However, here the state is retrieved just fine. 
// This is the function the child calls to update the state. 
textInputChangeHandler(event) { 
    // This console.log call shows the correct state! 
    console.log(this.state); 
    this.setState({ 
     titleInputValue: event.target.value, 
    }); 
} 

TextInput説明のためonChange={this.props.changeHandler.bind(this)}

の属性があります。

enter image description here

私はその後、asdを書き、状態が正常に最初の2回のconsole.logの呼び出しである、textInputChangeHandlerで検索しましたが、 handleSubmitで空です。

答えて

2

これは、イベントハンドラスコープがコンポーネントクラスレベルではないためです。コンポーネントがイベントを処理するとき、そのコンテキストは、親ではないコンポーネント(あなたの場合はTextInput)です。

あなたは、コンポーネントのクラススコープのこれにその機能をバインドする必要があります。JavaScriptを使用して

<TextInput 
     val={this.state.titleInputValue} 
     changeHandler={this.textInputChangeHandler.bind(this) } /> 

は、あなたが同様の機能のコンテキストを指定することができますバインドします。

+0

ありがとう、それは今動作します!私はあなたの答えを利用可能になると直ちにそれに印をつけます。 – KSHMR

+0

@Gudmundur私はそれを聞いて非常にうれしいです。 – Burimi

関連する問題