我有一個元素,一個名爲<NormalTextField/>
的子組件,但是如何從其父組件<Home/>
調用方法_handleFirstName
和_handleLastName
?我正在嘗試讓用戶輸入文本,並將其發送到Reducer中創建一個對象user
,該對象包含firstName
和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的方法嗎?