Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, {Component, PropTypes} from 'react';
- export default class InputStateMachine extends Component {
- constructor(props) {
- super(props);
- this.handleSubmit = this.handleSubmit.bind(this);
- this.goToState = this.goToState.bind(this);
- this.save = this.save.bind(this);
- this.state = {
- name: 'display',
- machine: this.generateState('display', props.initialValue),
- };
- }
- generateState(stateName, stateParam) {
- const previousState = this.state ? {...this.state.machine} : {};
- switch (stateName) {
- case 'display':
- return {
- processing: false,
- error: null,
- value: stateParam || previousState.value,
- editing: false,
- editValue: null,
- };
- case 'saving':
- return {
- processing: true,
- error: null, // Сброс предыдущей ошибки сохранения
- value: previousState.value,
- editing: true, // Отображение окна редактирования в процессе сохранения
- editValue: previousState.editValue,
- };
- case 'edit':
- return {
- processing: false,
- error: null,
- value: previousState.value,
- editing: true,
- editValue: stateParam,
- };
- case 'save_error':
- return {
- processing: false,
- error: stateParam,
- value: previousState.value,
- editing: true, // Оставляем окно редактирования открытым
- editValue: previousState.editValue,
- };
- case 'loading': // Идентично состоянию по умолчанию
- default:
- return {
- processing: true,
- error: null,
- value: null,
- editing: false,
- editValue: null,
- };
- }
- }
- goToState(stateName, stateParam) {
- this.setState({
- name: stateName,
- machine: this.generateState(stateName, stateParam),
- });
- }
- handleSubmit(e) {
- this.goToState('edit', e.target.value);
- }
- save(valueToSave) {
- this.goToState('saving');
- // Имитируем сохранение данных...
- setTimeout(() => this.goToState('display', valueToSave), 2000);
- }
- render() {
- const {processing, error, value, editing, editValue} = this.state.machine;
- if (processing) {
- return <p>Processing ...</p>;
- } else if (editing) {
- return (
- <div>
- <input
- type="text"
- onChange={this.handleSubmit}
- value={editValue || value}
- />
- {error && <p>Error: {error}</p>}
- <button onClick={() => this.save(editValue)}>Save</button>
- </div>
- );
- } else {
- return (
- <div>
- <p>{value}</p>
- <button onClick={() => this.goToState('edit', value)}>Edit</button>
- </div>
- );
- }
- }
- }
Add Comment
Please, Sign In to add comment