感谢花时间查看我的代码,我使用React.js创建一个搜索栏,一切正常,直到我尝试在构造函数中绑定inputChange。一旦onInputChange在构造函数中绑定,我就无法在表单文本字段中输入。我尝试使用console.log,它显示捕获了事件键击但文本输入字段中没有显示任何内容。
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { fetchWeather } from '../actions/index';
class SearchBar extends Component {
constructor(props) {
super(props);
this.state = { term: '' };
this.onInputChange = this.onInputChange.bind(this); *(if I comment out onInputChange bind statement then I can type in the form field)
this.onFormSubmit = this.onFormSubmit.bind(this);
}
onInputChange(event) {
console.log(event.target.value);
this.setState = ({ term: event.target.value });
}
onFormSubmit(event) {
event.preventDefault();
this.props.fetchWeather(this.state.term);
this.setState({ term: '' });
}
render() {
return (
<form onSubmit={this.onFormSubmit} className="input-group">
<input type="text"
placeholder="Five day forcast for your favorite cities"
className="form-control"
value={this.state.term}
onChange={this.onInputChange} /> *(tried this.onInputChange.bind(this) but same thing happened)
<span className="input-group-btn">
<button type="submit" className="btn btn- secondary">Submit</button>
</span>
</form>
);
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ fetchWeather }, dispatch);
}
export default connect(null, mapDispatchToProps)(SearchBar);
答案 0 :(得分:1)
为什么要将对象分配给setState方法?然后这个.term永远不会改变。
onInputChange(event) {
console.log(event.target.value);
this.setState({ term: event.target.value }); // <-- fixed it
}