设置间隔计时器以在React.js

时间:2017-10-02 02:53:27

标签: reactjs setinterval

我有一个函数,我想根据用户从下拉列表中选择的秒数每隔x秒触发一次。

该功能(当我输入数字时有效)

refreshNames(){
    setInterval(this.getNames, 1000);
  };

JSX:

<select id="timerInterval">
    <option value="5">1 sec</option>
    <option value="10">2 sec</option>
    <option value="15">3 sec</option>
</select>

如果我用{timer}替换1000,我怎样才能将{timer}设置为所选的值?

2 个答案:

答案 0 :(得分:0)

您可以将反应组件的本地状态维持在计时器值。由于用户将更改该值,因此间隔将更改。您需要处理select的onChange事件。

this.state = {
  timerInterval: 1000 //default value
}

handleIntervalChange = (e) => {
  const val = e.target.options[e.target.selectedIndex].value;  //not sure if this is correct but somehow you can get the value
  this.setState({timerInterval: val})
}

<select id="timerInterval" onChange={this.handleIntervalChange}>
...
</select>

refreshNames(){
    setInterval(this.getNames, this.state.timerInterval);
  };

答案 1 :(得分:0)

如果要使用setInterval,则需要清除运行间隔,然后使用新的间隔重新启动它。您可以改为使用setTimeout并再次在函数内调用超时到simulatesetInterval之类的

class App extends React.Component {
   state = {
      timerInterval: 1000
   }
   getNames = () => {
    console.log('names');
    setTimeout(this.getNames, this.state.timerInterval);
   }
   componentDidMount() {
      setTimeout(this.getNames, this.state.timerInterval);
   }
   handleChange = (e) => {
      const val = e.target.value;  
      console.log('interval', val*1000);
      this.setState({timerInterval: val*1000})
   }
   render() {
    return (
      <select id="timerInterval" onChange={this.handleChange}>
        <option value="1">1 sec</option>
        <option value="2">2 sec</option>
        <option value="3">3 sec</option>
     </select>
    )
   }
}

ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>