2016-08-03 17 views
1

子コンポーネントの<NormalTextField/>がありますが、親コンポーネント<Home/>からメソッド_handleFirstName_handleLastNameをどのように呼び出すことができますか?ユーザーにテキストを入力させようとしていて、firstNamelastNameを保持しているリデューサにuserオブジェクトを作成するために送信されます。親コンポーネント内のメソッドを子コンポーネントから呼び出す方法は?

私は、次のしている <Home/>

_handleFirstName(event){ 
    this.props.actions.updateFirstName(event.target.value) 
    } 

    _handleLastName(event){ 
    this.props.actions.updateLastName(event.target.value) 
    } 

render(){ 
return(
    <NormalTextField 
    hint='Enter First Name' 
    onChange={this._handleFirstName.bind(this)} 
    value={this.props.user.firstName} 
    /> 

    <NormalTextField 
    hint='Enter Last Name' 
    onChange={this._handleLastName.bind(this)} 
    value={this.props.user.lastName} 
    /> 

をその後、私の要素<NormalTextField/>で、

import React, { Component } from 'react' 

import { TextField } from 'material-ui' 
import { orange900 } from 'material-ui/styles/colors' 

class TextFieldLabel extends Component { 
    static propTypes = { 
    hint: React.PropTypes.string, 
    onChange: React.PropTypes.func 
    } 

    _handle(event){ 
    this.props.onChange(event.target.value) 
    } 


    render() { 
    var pr = this.props 
    var hint = pr.hint 
    var value = pr.value 

    return (
     <TextField 
     hintText={hint} 
     onChange={this._handle.bind(this)} 
     value={value} 
     /> 
    ) 
    } 
} 

export default NormalTextField 

しかし、ユーザーがテキストに入ると、私は次のエラーを取得する:_handleFirstName(event)ためUncaught: TypeError: Cannot read property 'value' of undefined。私は間違って何をしていますか?これは適切なアプローチですか、子コンポーネントが親のメソッドを呼び出すことは可能ですか?

答えて

2

あなたが見ている問題は、eventを受け入れるとevent.target.value_handleFirstNameに渡すことです。あなたはこれに_handle変更することができます:

_handle(event) { 
    this.props.onChange(event) 
    } 

または、理想的に、あなたはNormalTextFieldにイベントハンドラを削除し、ただのonChangeが直接小道具使用することができます。

スタートコンストラクタにバインド・コールを移動すると:

class TextFieldLabel extends Component { 
    static propTypes = { 
    hint: React.PropTypes.string, 
    onChange: React.PropTypes.func 
    } 

    // _handle removed 

    render() { 
    var pr = this.props 
    var hint = pr.hint 
    var value = pr.value 

    return (
     <TextField 
     hintText={hint} 
     onChange={this.props.onChange} // use prop directly 
     value={value} 
     /> 
    ) 
    } 
} 

constructor() { 
    super(); 
    this._handleFirstName = this._handleFirstName.bind(this); 
    this._handleLastName= this._handleLastName.bind(this); 
} 

_handleFirstName(event){ 
    this.props.actions.updateFirstName(event.target.value) 
    } 

    _handleLastName(event){ 
    this.props.actions.updateLastName(event.target.value) 
    } 

// remove .bind(this) from your onChange 
render(){ 
return(
    <NormalTextField 
    hint='Enter First Name' 
    onChange={this._handleFirstName} 
    value={this.props.user.firstName} 
    /> 

    <NormalTextField 
    hint='Enter Last Name' 
    onChange={this._handleLastName} 
    value={this.props.user.lastName} 
    /> 

はこれにあなたのNormalTextFieldを変更

関連する問題