[英]ReactJS - button onClick gets called during render
我有一個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(...):在現有狀態轉換期間(例如在
render
或其他組件的構造函數中)無法更新。 渲染方法應該是道具和狀態的純函數; 構造函數副作用是反模式,但可以移動到componentWillMount
。
對我來說,這看起來像onClick按鈕在組件仍在渲染時被調用。 我究竟做錯了什么?
這是因為您不是將函數傳遞給onClick事件,而是直接調用該函數。
嘗試這樣做:
<button onClick={() => { this.handleButton(60)}}>1min</button>
<button onClick={() => { this.handleButton(180)}}>3min</button>
<button onClick={() => { this.handleButton(300)}}>5min</button>
在這里找到答案: React onClick函數在渲染時觸發
希望能幫助到你!
如果你不想出於任何原因使用anon函數,第二種方法是直接在render函數中使用bind。 然后你可以刪除構造函數中的行:)
<button onClick={this.handleButton.bind(this, 60)}>1min</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.