gpt4 book ai didi

javascript - react 函数说 "is not a function"

转载 作者:数据小太阳 更新时间:2023-10-29 05:17:24 25 4
gpt4 key购买 nike

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

这是我正在使用的代码:

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。我在这里缺少什么?

最佳答案

应该是

<WeatherForm
updateInputValue={this.updateInputValue}
/>

常见相关问题:

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

关于javascript - react 函数说 "is not a function",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51066111/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com