我正在尝试使用天气和污染来改进应用。主要的想法是有2个提交按钮,重定向到其他网址。我已经尝试了一些选项,最后你看到的是关于制作2个onClick函数,但是我无法将数据传递给onFormSubmit函数。
import React, {Component} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {fetchWeather} from '../actions/index';
import { Link } from 'react-router';
import { reduxForm } from 'redux-form';
class SearchBar extends Component{
constructor(props){
super(props);
this.state = {term:''};
this.onInputChange= this.onInputChange.bind(this);
this.onFormSubmit = this.onFormSubmit.bind(this);
}
static contextTypes = {
router: React.PropTypes.object
};
onInputChange(event){
this.setState({term : event.target.value});
};
onFormSubmit(event){
event.preventDefault();
if (this.numberButton == 1){
return (this.props.fetchWeather(this.state.term)
.then(() => {
this.context.router.push('/')}));
} else if (this.numberButton == 2){
} else {
return console.log('Went wrong');
}
this.setState({term:''});
};
render(){
return (
<div>
<form
onSubmit={this.onFormSubmit}
className="input-group">
<input
placeholder="Put here a US city name"
className="form-control"
value={this.state.term}
onChange={this.onInputChange}
/>
<span className="input-group-btn" role="group">
<button type="submit" name="button1" value="Weather" className="btn btn-secondary btn-success" onClick={ () => a=1} >Weather</button>
<button type="submit" name="button2" value="Polution" className="btn btn-secondary btn-info" onClick={() => a =2} >Polution</button>
</span>
</form>
</div>
)
}
}
function mapDispatchToProps(dispatch){
return bindActionCreators({fetchWeather}, dispatch);
}
export default connect(null, mapDispatchToProps)(SearchBar);
答案 0 :(得分:0)
有两种不同的方法可以解决这个问题:
1)在每个按钮上放置一个id(例如'weather-button'),然后检查e.target.id ==='weather-button'而不是this.numberButton == 1.我没有看到这个.numberButton在任何地方声明,因此条件永远不会成立。
2)完全删除表单包装器,并为每个按钮提供不同的handleClick。
handleWeatherClick = e => { ... }
handlePollutionClick = e => { ... }
...
<span className="input-group-btn" role="group">
<button className="btn btn-secondary btn-success" onClick={this.handleWeatherClick}>
Weather
</button>
<button className="btn btn-secondary btn-info" onClick={this.handlePollutionClick}>
Pollution
</button>
</span>