Javascript 为什么我的函数被认为是未定义的?
为什么我的函数Javascript 为什么我的函数被认为是未定义的?,javascript,reactjs,Javascript,Reactjs,为什么我的函数onInputBlur被认为是未定义的?我想这是难以置信的愚蠢,但我已经尝试在构造函数和其他变体中进行绑定 import React from 'react'; class StateSelect extends React.Component { constructor(props) { super(props) this.state = {} } onInputBlur = (event) => {
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>
)
}
}
从“React”导入React;
类StateSelect扩展了React.Component{
建造师(道具){
超级(道具)
this.state={}
}
onInputBlur=(事件)=>{
让choiceType=event.target.id.toString()
让选项=event.target.value
console.log(this.props.state)
}
render(){
const{styles}=this.props
返回(
陈述
{Object.keys(States).map((key)=>{
返回({States[key]})
})}
)
}
}
您需要编写onBlur={this.onInputBlur}
。您可以使用this
关键字访问类属性
片段
render() {
const { styles } = this.props
return (
<div style={styles.formInput}>
<select id="state" name="state" onChange={this.props.saveInputVal} onBlur={this.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>
)
}
render(){
const{styles}=this.props
返回(
陈述
{Object.keys(States).map((key)=>{
返回({States[key]})
})}
)
}
因为绑定onInputBlur
是一个类函数,需要使用this
访问它(也需要使用this
访问bind()
),您必须这样说。onInputBlur@SterlingArcher:由于它是一个箭头函数,bind
是不必要的。@T.J.Crowder很好,请求帮助时错过了这一点,请花时间以合理、一致的方式格式化和缩进代码。(不寻求帮助也是个好主意。)