2017-01-02 108 views
1

我有一個表格type="range"。現在我想添加3個按鈕來改變表單的相同值。出於某種原因,onClick事件按鈕似乎在調用渲染函數時被重複調用。ReactJS - 按鈕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或其他組件的 構造函數中)無法更新。渲染方法應該是道具和純粹功能的狀態;構造函數的副作用是反模式,但可以將 移動到componentWillMount

對我來說,這看起來像組件仍在渲染時調用onClick按鈕。我究竟做錯了什麼?

+0

[上呈現陣營的onClick功能火災(可能的重複http://stackoverflow.com/questions/33846682/react-onclick-function-fires-on-線渲染) – Swapnil

回答

7

這是因爲不是將函數傳遞給事件onClick,而是直接調用該函數。

嘗試做這種方式:

<button onClick={() => { this.handleButton(60)}}>1min</button> 
<button onClick={() => { this.handleButton(180)}}>3min</button> 
<button onClick={() => { this.handleButton(300)}}>5min</button> 

找到答案在這裏:React onClick function fires on render

希望它能幫助!

2

如果您不想使用匿名函數出於任何原因,第二種方法是直接在渲染函數中使用綁定。然後你可以刪除你的構造:)

<button onClick={this.handleButton.bind(this, 60)}>1min</button>