Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/410.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用ref在react.js中的两个按钮之间切换?_Javascript_Reactjs_React Native_React Redux_React Router - Fatal编程技术网

Javascript 如何使用ref在react.js中的两个按钮之间切换?

Javascript 如何使用ref在react.js中的两个按钮之间切换?,javascript,reactjs,react-native,react-redux,react-router,Javascript,Reactjs,React Native,React Redux,React Router,我正在创建一个秒表应用程序。当我单击“开始”和“停止”按钮时,秒表会工作,但只要我按下空格键,它就会在0处重新启动,并开始加速秒表 class Home extends React.Component { constructor(props) { super(props); this.state = {milliSecondsElapsed: 0}; this.updateState = this.updateState.bind(this

我正在创建一个秒表应用程序。当我单击“开始”和“停止”按钮时,秒表会工作,但只要我按下空格键,它就会在0处重新启动,并开始加速秒表

class Home extends React.Component {
    constructor(props) {
        super(props);
        this.state = {milliSecondsElapsed: 0};
        this.updateState = this.updateState.bind(this);
        this.textInput = React.createRef();
    }
    textInput = () => {
        clearInterval(this.timer);
    }
    updateState(e) {
        this.setState({milliSecondsElapsed: e.target.milliSecondsElapsed })
    }
    ...
    keyPress = (e) => {
        // spacebar
        if (e.keyCode == 32) {
            handleStop();
        }
    }
    ...
    handleStart = () => {
        this.setState({
            milliSecondsElapsed: (0)
        });
        this.timer = setInterval(() => {
            this.setState({
                milliSecondsElapsed: (this.state.milliSecondsElapsed + 1)
            });
        }, 10)
    }
    handleStop = () => {
        clearInterval(this.timer);
    }
    render() {
        return (    
            <div className="index">
                <input value = {this.state.milliSecondsElapsed} onChange = {this.updateState} ref={this.textInput}/>
                <button onClick = {this.handleStart}>START</button>
                <button onClick = {this.handleStop}>STOP</button>
            </div>
        );
    }

}
class Home扩展了React.Component{
建造师(道具){
超级(道具);
this.state={millissecondselapsed:0};
this.updateState=this.updateState.bind(this);
this.textInput=React.createRef();
}
text输入=()=>{
clearInterval(这个计时器);
}
房地产(东){
this.setState({millissecondselapsed:e.target.millissecondselapsed})
}
...
按键=(e)=>{
//空格键
如果(e.keyCode==32){
手柄();
}
}
...
handleStart=()=>{
这是我的国家({
毫秒已关闭:(0)
});
this.timer=setInterval(()=>{
这是我的国家({
毫秒selapsed:(this.state.millissecondselapsed+1)
});
}, 10)
}
handleStop=()=>{
clearInterval(这个计时器);
}
render(){
报税表(
开始
停止
);
}
}

我和裁判们试过一些方法,但没有一种方法能让裁判做我想做的事情。基本上,我想点击空格键启动秒表,然后再次按下它停止秒表。我希望在启动秒表后加载页面时将焦点放在开始按钮和停止按钮上。

在使用React编程时,始终评估是否可以在不使用refs的情况下完成任务

从:

避免对任何可以声明式完成的操作使用引用

在这个场景中,您并没有真正的引用,只是在窗口上有一个事件监听器来检测按键。组件卸载时,根据需要进行清洁。您可以在按键功能上实现一些逻辑,以评估计时器应该停止还是启动

this.state = { 
  milliSecondsElapsed: 0,
  timerInProgress: false // state to detect whether timer has started
};

componentDidMount() {
    window.addEventListener("keypress", this.keyPress);
}

keyPress = (e) => {
    // some logic to assess stop/start of timer
    if (this.state.milliSecondsElapsed === 0) {
        this.handleStart();
    } else if (this.state.timerInProgress === false) {
        this.handleStart();
    } else {
        this.handleStop();
    }
};

<button onClick={this.handleStart} ref={(ref) => (this.startBtn = ref)}>
    START
</button>
<button onClick={this.handleStop} ref={(ref) => (this.startBtn = ref)}>
    STOP
</button>
this.state={
毫秒秒秒:0,
timerInProgress:false//状态,用于检测计时器是否已启动
};
componentDidMount(){
window.addEventListener(“keypress”,this.keypress);
}
按键=(e)=>{
//评估定时器停止/启动的一些逻辑
if(this.state.millissecondselapsed==0){
这个;
}else if(this.state.timerInProgress==false){
这个;
}否则{
这个。handleStop();
}
};
(this.startBtn=ref)}>
开始
(this.startBtn=ref)}>
停止
代码沙盒:


不过,为了完成回答,您可以使用上面使用ref的相同逻辑,只需在每个按钮上附加一个ref

keyPress = (e) => {
  // some logic to assess stop/start of timer
  if (this.state.milliSecondsElapsed === 0) {
    this.startBtn.click();
  } else if (this.state.timerInProgress === false) {
    this.startBtn.click();
  } else {
    this.stopBtn.click();
  }
};

<button onClick={this.handleStart} ref={(ref) => (this.startBtn = ref)}>
  START
</button>
<button onClick={this.handleStop} ref={(ref) => (this.stopBtn = ref)}>
  STOP
</button>
keyPress=(e)=>{
//评估定时器停止/启动的一些逻辑
if(this.state.millissecondselapsed==0){
this.startBtn.click();
}else if(this.state.timerInProgress==false){
this.startBtn.click();
}否则{
this.stopBtn.click();
}
};
(this.startBtn=ref)}>
开始
(this.stopBtn=ref)}>
停止

要具体地“切换”按钮的焦点,您可以选择在每个按钮上分配一个
ref
,然后在调用“开始”和“停止”计时器处理程序并设置新状态时调用相反按钮的事件

this.state = { 
  milliSecondsElapsed: 0,
  timerInProgress: false // state to detect whether timer has started
};

componentDidMount() {
    window.addEventListener("keypress", this.keyPress);
}

keyPress = (e) => {
  // some logic to assess stop/start of timer
  if (this.state.milliSecondsElapsed === 0) {
    this.startBtn.click();
  } else if (this.state.timerInProgress === false) {
    this.startBtn.click();
  } else {
    this.stopBtn.click();
  }
};

handleStart = () => {
  if (this.state.timerInProgress === true) return;

  this.setState({
    milliSecondsElapsed: 0
  });
  this.timer = setInterval(() => {
    this.setState(
      {
        milliSecondsElapsed: this.state.milliSecondsElapsed + 1,
        timerInProgress: true
      },
      () => {
        this.stopBtn.focus(); /* switch focus to STOP button */
      }
    );
  }, 10);
};
handleStop = () => {
  this.setState(
    {
      timerInProgress: false
    },
    () => {
      clearInterval(this.timer);
      this.startBtn.focus(); /* switch focus to START button */
    }
  );
};

<button onClick={this.handleStart} ref={(ref) => (this.startBtn = ref)}>
  START
</button>
<button onClick={this.handleStop} ref={(ref) => (this.stopBtn = ref)}>
  STOP
</button>
this.state={
毫秒秒秒:0,
timerInProgress:false//状态,用于检测计时器是否已启动
};
componentDidMount(){
window.addEventListener(“keypress”,this.keypress);
}
按键=(e)=>{
//评估定时器停止/启动的一些逻辑
if(this.state.millissecondselapsed==0){
this.startBtn.click();
}else if(this.state.timerInProgress==false){
this.startBtn.click();
}否则{
this.stopBtn.click();
}
};
handleStart=()=>{
if(this.state.timerInProgress==true)返回;
这是我的国家({
毫秒:0
});
this.timer=setInterval(()=>{
这是我的国家(
{
毫秒selapsed:this.state.millissecondselapsed+1,
时间进程:正确
},
() => {
此.stopBtn.focus();/*将焦点切换到停止按钮*/
}
);
}, 10);
};
handleStop=()=>{
这是我的国家(
{
timerInProgress:错误
},
() => {
clearInterval(这个计时器);
此.startBtn.focus();/*将焦点切换到开始按钮*/
}
);
};
(this.startBtn=ref)}>
开始
(this.stopBtn=ref)}>
停止

CodeSandBox:

我已经实现了您在第一个示例中使用的componentDidMount。似乎它仍然专注于开始按钮,因为同样的事情正在发生。当我按下空格键时,计时器会启动,但当我再次按下时,它会以两倍于停止的速度再次启动。我建议您防止默认的
mousedown
事件
e.preventDefault()}onClick={this.handleStart}>START