Javascript ReactJS-在渲染期间调用按钮onClick
我有一个带有Javascript ReactJS-在渲染期间调用按钮onClick,javascript,reactjs,ecmascript-6,Javascript,Reactjs,Ecmascript 6,我有一个带有type=“range”的表单。现在,我想添加3个按钮,它们改变表单所做的相同值。出于某种原因,按钮onClick事件似乎在调用render函数时被反复调用 这是我的组件: class Slider extends Component { constructor(props) { super(props); this.handleChange = this.handleChange.bind(this); this.handl
type=“range”
的表单。现在,我想添加3个按钮,它们改变表单所做的相同值。出于某种原因,按钮onClick事件似乎在调用render函数时被反复调用
这是我的组件:
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(…):无法在现有状态期间更新
转换(例如在渲染
或其他组件的
构造函数)。渲染方法应该是道具和工具的纯功能
国家;构造函数的副作用是一种反模式,但可以移动
到组件将装入
对我来说,这看起来像是在组件仍在渲染时调用按钮onClick。我做错了什么?这是因为您没有将函数传递给事件onClick,而是直接调用函数
试着这样做:
<button onClick={() => { this.handleButton(60)}}>1min</button>
<button onClick={() => { this.handleButton(180)}}>3min</button>
<button onClick={() => { this.handleButton(300)}}>5min</button>
{this.handleButton(60)}}>1分钟
{此把手按钮(180)}}>3分钟
{此车把扣(300)}}>5分钟
在这里找到了答案:
希望有帮助 如果出于任何原因不想使用anon函数,第二种方法是在render函数处直接使用bind。然后可以在构造函数中删除行:)
1min
我一直在研究这个问题,因为我与OP有相同的问题,在其他类似的线程上,人们建议绑定这个
,而不是在渲染方法内部绑定。
<button onClick={this.handleButton.bind(this, 60)}>1min</button>