我正在努力将一些React应用分解为较小的组件。在分离代码之前,一切都按计划进行。我现在尝试调用一个函数onChange
,该函数先调用一个函数,然后再将该函数作为prop
进行调用。我正在绑定类似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
。我在这里想念什么?
答案 0 :(得分:2)
应该是
<WeatherForm
updateInputValue={this.updateInputValue}
/>
答案 1 :(得分:1)
您的子组件仅具有updateInput
的属性作为方法,而您正在子组件中调用this.props.updateInputValue()
。尝试使用相同的名称。
当您没有将this.props.inputValue
作为道具传递给子组件时,您也在子组件中调用inputValue
。
我要简化代码并避免将来发生此类错误的方法是,在onChange事件中直接调用this.props.updateInputValue
,例如:onChange={e => this.props.updateInputValue(e)}
然后,您将绑定另一个组件方法的工作保存在构造函数中。这也将使您的单元测试更加容易,但这是另一个讨论。