| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- import React, { Component } from 'react';
- import PropTypes from 'prop-types';
- import classNames from 'classnames';
- import Field from 'components/Field';
- import FieldView from 'components/FieldView';
- import './style.scss';
- export default class CrudField extends Component {
- static propTypes = {
- field: PropTypes.string.isRequired,
- pending: PropTypes.bool,
- type: PropTypes.string.isRequired,
- value: PropTypes.string.isRequired,
- onEditStart: PropTypes.func.isRequired,
- onEditEnd: PropTypes.func.isRequired
- };
- constructor(props) {
- super(props);
- this.state = {
- editing: false,
- editValue: props.value
- };
- }
- onChange = event => {
- this.setState({
- editValue: event.target.value
- });
- };
- onEditStart = () => {
- this.setState({
- editing: true
- });
- };
- onEditEnd = () => {
- if (this.state.editValue !== this.props.value) {
- this.props.onEditEnd(this.props.field, this.state.editValue);
- }
- this.setState({
- editing: false
- });
- };
- componentDidUpdate(prevProps) {
- if (prevProps.value !== this.props.value) {
- this.setState({
- editing: false,
- editValue: this.props.value
- });
- }
- }
- render() {
- const {
- pending,
- type,
- value
- } = this.props;
- if (this.state.editing) {
- return (
- <Field className="crud-field editing"
- disabled={pending}
- type={type}
- value={this.state.editValue}
- onChange={this.onChange}
- onBlur={this.onEditEnd}
- />
- );
- }
- const className = classNames('crud-field', {
- 'multi-line': type === 'textarea',
- 'single-line': ['text', 'number'].includes(type),
- pending
- });
- return (
- <FieldView
- type={type}
- value={value}
- className={className}
- onClick={this.onEditStart}
- />
- );
- }
- }
|