状态机在react简单应用

XState

使用xstate提供的 Machine、useMachine

App.js

import React from 'react';
import logo from './logo.svg';
import './App.css';
import { Machine } from 'xstate';
import { useMachine } from '@xstate/react';

import { RedLight, GreenLight, YellowLight } from './Light'

const LIGHT_STATES = {
  RED: 'RED',
  YELLOW: 'YELLOW',
  GREEN: 'GREEN',
}

const LIGHT_CLICK = {
  CLICK: 'CLICK'
}

const lightMachine = Machine({
  initial: LIGHT_STATES.RED,
  states: {
    [LIGHT_STATES.RED]: {
      on: {
        [LIGHT_CLICK.CLICK]: LIGHT_STATES.YELLOW,
      }
    },
    [LIGHT_STATES.YELLOW]: {
      on: {
        [LIGHT_CLICK.CLICK]: LIGHT_STATES.GREEN,
      }
    },
    [LIGHT_STATES.GREEN]: {
      [LIGHT_CLICK.CLICK]: LIGHT_STATES.RED
    }
  }
})

function App() {
  const [state, send] = useMachine(lightMachine)
  return (
    
{state.matches(LIGHT_STATES.RED) && } {state.matches(LIGHT_STATES.YELLOW) && } {state.matches(LIGHT_STATES.GREEN) && }
); } export default App;

App.css

.App {
  text-align: center;
}

.light {
  display: inline-block;
  width: 30px;
  height: 30px;
  border-radius: 50%;
  margin-right: 15px;
}

.red {
  background-color: red;
}

.yellow {
  background-color: yellow;
}

.green {
  background-color: green;
}

Light.js

import React from 'react'

export function RedLight() {
  return 
}

export function YellowLight() {
  return 
}

export function GreenLight() {
  return 
}

你可能感兴趣的:(状态机在react简单应用)