【发布时间】:2017-05-16 16:33:30
【问题描述】:
我有一个带有type="range" 的表格。现在我想添加 3 个按钮来更改与表单相同的值。出于某种原因,按钮 onClick 事件似乎在调用渲染函数时被重复调用。
这是我的组件:
class Slider extends Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleButton = this.handleButton.bind(this);
}
handleChange() {
this.props.onSetCountdown(parseInt(this.refs.seconds.value, 10));
}
handleButton(value) {
this.props.onSetCountdown(parseInt(value, 10));
}
render() {
return(
<div>
<form className={styles.ttSlider} ref="form">
<input max="480" min="60" name="slider" onChange={this.handleChange} ref="seconds" type="range" value={this.props.totalSeconds}/>
<button onClick={this.handleButton(60)}>1min</button>
<button onClick={this.handleButton(180)}>3min</button>
<button onClick={this.handleButton(300)}>5min</button>
</form>
</div>
)
}
}
Slider.propTypes = {
totalSeconds: React.PropTypes.number.isRequired,
onSetCountdown: React.PropTypes.func.isRequired
};
这是来自父组件:
handleSetCountdown(seconds) {
this.setState({
count: seconds
});
}
从父组件渲染:
<Slider totalSeconds={count} onSetCountdown={this.handleSetCountdown}/>
这是我得到的错误:
警告:setState(...):在现有状态期间无法更新 过渡(例如在
render或其他组件的 构造函数)。渲染方法应该是 props 的纯函数和 状态;构造函数副作用是一种反模式,但可以移动 到componentWillMount。
对我来说,这看起来像是在组件仍在渲染时调用了 onClick 按钮。我做错了什么?
【问题讨论】:
标签: javascript reactjs ecmascript-6