jus*_*Dan 6 javascript reactjs
我正在努力将一些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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
因此,当我在输入中键入一个字符而不是控制台日志记录时hit,它显示为Uncaught TypeError: this.props.updateInputValue is not a function。我在这里想念什么?
它应该是
<WeatherForm
updateInputValue={this.updateInputValue}
/>
Run Code Online (Sandbox Code Playgroud)
updateInput您的子组件仅具有作为方法的属性,并且您this.props.updateInputValue()在子组件中调用。尝试用相同的名字称呼它们。
this.props.inputValue当您不将子组件inputValue作为 props传递时,您也会调用子组件。
为了简化代码并可能避免将来出现此类错误,我要做的就是直接调用this.props.updateInputValueonChange 事件,如下所示\xef\xbc\x9a onChange={e => this.props.updateInputValue(e)}\n然后你可以保存在构造函数中绑定另一个组件方法的工作。它还将使您的单元测试更容易,但这是另一个讨论。
| 归档时间: |
|
| 查看次数: |
6250 次 |
| 最近记录: |