如何从Child组件中调用Parent组件中的方法?

时间:2016-08-03 02:49:43

标签: javascript html reactjs redux react-jsx

我有一个元素,一个名为<NormalTextField/>的子组件,但是如何从其父组件_handleFirstName调用方法_handleLastName<Home/>?我尝试让用户输入文字,然后将其发送给在Reducer中创建一个包含userfirstName的对象lastName

<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

但是,一旦用户输入文字,我就会收到以下错误:Uncaught: TypeError: Cannot read property 'value' of undefined _handleFirstName(event)。我究竟做错了什么?这是正确的方法,Child组件可以调用Parent的方法吗?

1 个答案:

答案 0 :(得分:2)

您遇到的问题是,当您接受event.target.value时,您已将_handleFirstName传递给event。您可以将_handle更改为:

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

或者,理想情况下,您可以删除NormalTextField中的事件处理程序,并直接使用onChange道具。

首先将bind调用移动到构造函数:

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更改为:

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}
      />
    )
  }
}