【问题标题】:Why is my function considered undefined?为什么我的函数被认为是未定义的?
【发布时间】: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


【解决方案1】:

你需要写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>
    )
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-26
    • 2020-06-05
    • 2021-10-26
    • 1970-01-01
    • 2022-01-16
    • 2017-12-03
    • 2016-10-27
    • 2016-04-22
    相关资源
    最近更新 更多