无法调用在组件内部声明的函数

时间:2019-09-02 17:16:40

标签: javascript reactjs events redux

尝试调用组件内部声明的函数时出现错误。这是错误消息:Uncaught TypeError:无法读取未定义的属性'handleClick'

class LanguageDropDown extends Component {
  constructor(props) {
    super(props);

    this.state = {languageValue: ""};
    this.handleLanguageClick = this.handleLanguageClick.bind(this);
  }
  handleLanguageClick = (languageKey) => {
    this.setState({ languageValue: languageKey});
  }

  render() {
    const {intl, value, onChange, onFocus, onBlur, onClick} = this.props;
    return (
      <React.Fragment>
        {
          map(languageWhitelist, function(Key) {
            return (
              <option onClick={this.handleLanguageClick(Key)}
              key={Key} value={Key}></option>
             );
            }, this)
          }
      </React.Fragment>
    );
  }

}

2 个答案:

答案 0 :(得分:0)

这应该有效

class LanguageDropDown extends Component {
  state = { languageValue: '' };

  _handleLanguageClick(languageValue) {
    this.setState({ languageValue });
  };

  render() {
    const { intl, value, onChange, onFocus, onBlur, onClick } = this.props;

    return (
      <React.Fragment>
        {languageWhitelist.map(language => (
          <option
            onClick={() => this._handleLanguageClick(language)}
            key={language}
          >
            {language}
          </option>
        ))}
      </React.Fragment>
    );
  }
}

答案 1 :(得分:0)

通过在类内部使用箭头功能,它会自动绑定到该类, 因此只需从构造函数中删除绑定语句。 并将 onClick 道具设置为回调函数。

class LanguageDropDown extends Component {
  constructor(props) {
    super(props);

    this.state = { languageValue: '' };
  }

  _handleLanguageClick = languageValue => {
    this.setState({ languageValue });
  };

  render() {
    const { intl, value, onChange, onFocus, onBlur, onClick } = this.props;

    return (
      <React.Fragment>
        {languageWhitelist.map(language => (
          <option
            onClick={() => this._handleLanguageClick(language)}
            key={language}
          >
            {language}
          </option>
        ))}
      </React.Fragment>
    );
  }
}