首页 > 解决方案 > 如何创建具有多种状态的按钮?

问题描述

我是 React Native 的初学者,我需要一个按钮来拥有四种状态。

四种状态是接受、召回、开始和关闭。

它将按如下方式工作:

按“接受”-> 将变为“召回”

按“召回”-> 将变为“开始”

按“开始”-> 将变为“关闭”

每次按下按钮时,我都会将状态发送到我的数据库,以便保存所有操作,每个操作都以各自的小时、分钟和秒为单位。

我不知道该怎么做,所以我没有任何代码可以在这里发布,我做了一些研究,但我找不到合适的关键词来找到我需要的东西。

先感谢您。

标签: javascriptreact-native

解决方案


这是一个关于 React 的实时示例(在 react-native 中应该几乎相同) https://codepen.io/anon/pen/gNJOvL?editors=0010

class Button extends React.Component {
  state = {
    type: 'Accept'
  }

  types = ["Accept", "Recall", "Start", "Close"];

  doCall = (type) => {
    // requests here
    const nextType = this.types[this.types.indexOf(this.state.type) + 1];
    if (nextType) {
      this.setState({type: nextType});
    } else {
      // action you want to do if "Close" is pressed
    }
  }

  render() {
    const {type} = this.state;
    return (<button
              onClick={() => this.doCall(type)}
            >
              {type}
            </button>);
  }
}

React.render(<Button />, document.getElementById('app'));

推荐阅读