index.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. import React, { Component } from 'react';
  2. import PropTypes from 'prop-types';
  3. import classNames from 'classnames';
  4. import Field from 'components/Field';
  5. import FieldView from 'components/FieldView';
  6. import './style.scss';
  7. export default class CrudField extends Component {
  8. static propTypes = {
  9. field: PropTypes.string.isRequired,
  10. pending: PropTypes.bool,
  11. type: PropTypes.string.isRequired,
  12. value: PropTypes.string.isRequired,
  13. onEditStart: PropTypes.func.isRequired,
  14. onEditEnd: PropTypes.func.isRequired
  15. };
  16. constructor(props) {
  17. super(props);
  18. this.state = {
  19. editing: false,
  20. editValue: props.value
  21. };
  22. }
  23. onChange = event => {
  24. this.setState({
  25. editValue: event.target.value
  26. });
  27. };
  28. onEditStart = () => {
  29. this.setState({
  30. editing: true
  31. });
  32. };
  33. onEditEnd = () => {
  34. if (this.state.editValue !== this.props.value) {
  35. this.props.onEditEnd(this.props.field, this.state.editValue);
  36. }
  37. this.setState({
  38. editing: false
  39. });
  40. };
  41. componentDidUpdate(prevProps) {
  42. if (prevProps.value !== this.props.value) {
  43. this.setState({
  44. editing: false,
  45. editValue: this.props.value
  46. });
  47. }
  48. }
  49. render() {
  50. const {
  51. pending,
  52. type,
  53. value
  54. } = this.props;
  55. if (this.state.editing) {
  56. return (
  57. <Field className="crud-field editing"
  58. disabled={pending}
  59. type={type}
  60. value={this.state.editValue}
  61. onChange={this.onChange}
  62. onBlur={this.onEditEnd}
  63. />
  64. );
  65. }
  66. const className = classNames('crud-field', {
  67. 'multi-line': type === 'textarea',
  68. 'single-line': ['text', 'number'].includes(type),
  69. pending
  70. });
  71. return (
  72. <FieldView
  73. type={type}
  74. value={value}
  75. className={className}
  76. onClick={this.onEditStart}
  77. />
  78. );
  79. }
  80. }