【发布时间】:2018-02-12 17:29:53
【问题描述】:
为什么我的函数onInputBlur 被认为是未定义的?我想这非常愚蠢,但我尝试在构造函数和其他变体中进行绑定。
import React from 'react';
class StateSelect extends React.Component {
constructor(props) {
super(props)
this.state = {}
}
onInputBlur = (event) => {
let choiceType = event.target.id.toString()
let choice = event.target.value
console.log(this.props.state)
}
render() {
const { styles } = this.props
return (
<div style={styles.formInput}>
<select id="state" name="state" onChange={this.props.saveInputVal} onBlur={onInputBlur} style={styles.input}>
<option value disabled selected>State</option>
{Object.keys(States).map((key) => {
return ( <option key={key} value={key}>{States[key]}</option> )
})}
</select>
</div>
)
}
}
【问题讨论】:
-
因为绑定。
onInputBlur是一个类函数,需要用this访问(也可以用bind()和this访问) -
你不得不说this.onInputBlur
-
@SterlingArcher:因为它是箭头函数,所以
bind是不必要的。 -
@T.J.Crowder 好点,错过了
-
寻求帮助时,请花时间以合理、一致的方式格式化和缩进您的代码。 (当不寻求帮助时也是个好主意。)
标签: javascript reactjs