【发布时间】:2017-12-06 18:29:01
【问题描述】:
我有一个带有 4 个无线电输入的表单。我希望使用检查输入的值更新组件状态。
当前输入是检查值后面的一个值(即直到第二次点击才开始正确更新状态)。
如何让它在第一次点击时设置状态?
component.js
import React, { Component } from 'react';
class Graph extends React.Component {
constructor(props) {
super(props);
this.state = {
option: null
};
}
setOption(value) {
this.setState({option: value});
}
render() {
return (
<form>
<input
type="radio"
name="option"
onChange={(e) => this.setOption('tmax_C')}
checked={ this.state.option === 'tmax_C' }
value="tmax_C" />
<label htmlFor="option">Max Temp.</label>
<input type="radio"
name="option"
onChange={(e) => this.setOption('tmin_C')}
checked={ this.state.option === 'tmin_C' }
value="tmin_C" />
<label htmlFor="option">Min Temp</label>
<input type="radio"
name="option"
onChange={(e) => this.setOption('rain_mm')}
checked={ this.state.option === 'rain_mm' }
value="rain_mm" />
<label htmlFor="option">Rain mm</label>
<input type="radio"
name="option"
onChange={(e) => this.setOption('sunshine_hours')}
checked={ this.state.option === 'sunshine_hours' }
value="sunshine_hours" />
<label htmlFor="option">Sunshine Hours</label>
</form>
);
}
}
export default Graph;
【问题讨论】:
-
你需要像
setOption = (value) => { ... }这样声明函数setOption,否则你需要在构造函数中绑定它。 -
我也不想用这个
onChange={(e) => this.setOption('xxxx')}inline...建议改用函数
标签: javascript reactjs