首页 > 解决方案 > React 函数说“不是函数”

问题描述

我正在努力将一个小的反应应用程序分解成更小的组件。在分离代码之前,一切都按计划进行。我现在正在尝试调用一个函数,该函数onChange调用一个函数,然后将一个函数调用为prop. 我正在绑定这样的函数,this.updateInput = this.updateInput.bind(this);但我仍然无法弄清楚我错过了什么。我在这里尝试了最近的一篇文章(React:将函数传递给子组件),但错误仍然存​​在。任何帮助都很棒。

这是我正在使用的代码:

class Weather extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      city: '',
      details: []
    };

    this.updateInputValue = this.updateInputValue.bind(this);
  }

  updateInputValue(e) {
    this.setState({
      city: e.target.value
    });
    console.log('hit')
  }

  render() {
    return (
      <div className={style.container + ' ' + style.bodyText}>
        <WeatherForm
          updateInput={this.updateInputValue}
        />
      </div>
    );
  }
}


class WeatherForm extends React.Component {
  constructor(props) {
    super(props);
    this.updateInput = this.updateInput.bind(this); 
  }

  updateInput(e) {
    this.props.updateInputValue(e);
  }

  render() {
    return (
      <div className={style.weatherForm}>
        <form action='/' method='GET'>
          <input ref='city' value={this.props.inputValue} onChange={e => this.updateInput(e)} type='text' placeholder='Search city' />
        </form>
      </div>
    );
  }
}

因此,当我在输入中键入一个字符而不是控制台记录hit时,它会显示Uncaught TypeError: this.props.updateInputValue is not a function. 我在这里想念什么?

标签: javascriptreactjs

解决方案


它应该是

<WeatherForm
          updateInputValue={this.updateInputValue}
        />

常见相关问题:

同样的“不是函数”错误也可能是错误使用道具引起的,如this question所示


推荐阅读