【发布时间】:2017-10-01 22:55:53
【问题描述】:
我开始学习 React,但我很难找出这个错误。 我有一个父组件 Weather 和一个子组件 WeatherForm。从父组件中,我为子组件设置了一个属性。子组件是一个表单,目标是从输入中获取文本,当用户单击提交按钮时,输入文本被传递给父组件的函数,该函数显示带有文本的警报。
这是父组件:
const WeatherForm = require('WeatherForm');
const WeatherMessage = require('WeatherMessage');
class Weather extends Component {
constructor(props) {
super(props);
this.state = {
location: ''
};
this.handleSearch = this.handleSearch.bind(this);
}
render() {
return (
<div>
<h3>Weather component</h3>
<WeatherForm onSearch={this.handleSearch} />
<WeatherMessage />
</div >
);
}
handleSearch(value) {
alert(value);
}
}
这是子组件:
class WeatherForm extends Component {
constructor(props) {
super(props);
this.onFormSubmit = this.onFormSubmit.bind(this);
}
render() {
return (
<div>
<form onSubmit={this.onFormSubmit}>
<input type="text" placeholder="Enter a city name" ref="location" onChange={this.onFormSubmit}/>
<button>Get weather</button>
</form>
</div>
);
}
onFormSubmit(e) {
e.preventDefault();
let location = this.refs.location;
if (location.value && location.value.length > 0) {
this.refs.location.value = '';
props.onSearch(location.value);
}
}
}
但是当我点击提交按钮时,我收到了这个错误:
props.onSearch 不是函数
我哪里出错了?
我还在另一个组件中的路由中使用父组件 Weather,例如 <Route exact path="/" component={Weather} />
谢谢大家
【问题讨论】:
标签: reactjs react-router