Counter.jsx 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. import React, { memo } from "react";
  2. import styled, { css } from "styled-components";
  3. const CounterPane = styled.div`
  4. ${({ color }) => css`
  5. background-color: ${color};
  6. padding: 0.2em;
  7. text-align: center;
  8. border-radius: 3px;
  9. box-shadow: 4px 4px 5px 0px rgb(0, 0, 0, 0.3);
  10. .item-library__component & {
  11. transform: scale(0.7);
  12. }
  13. button {
  14. padding: 1rem;
  15. }
  16. input {
  17. width: 2em;
  18. }
  19. h3 {
  20. user-select: none;
  21. padding: 0;
  22. margin: 0;
  23. }
  24. div {
  25. display: flex;
  26. justify-content: space-between;
  27. flex-direction: row;
  28. align-items: center;
  29. }
  30. `}
  31. `;
  32. const Counter = ({
  33. value = 0,
  34. color = "#CCC",
  35. label = "",
  36. textColor = "#000",
  37. fontSize = "22",
  38. setState,
  39. }) => {
  40. const setValue = (e) => {
  41. let value = parseInt(e.target.value, 10);
  42. if (isNaN(value)) {
  43. value = 0;
  44. }
  45. setState((prevState) => ({
  46. ...prevState,
  47. value: value,
  48. }));
  49. };
  50. const increment = () => {
  51. setState((prevState) => ({
  52. ...prevState,
  53. value: (prevState.value || 0) + 1,
  54. }));
  55. };
  56. const decrement = () => {
  57. setState((prevState) => ({
  58. ...prevState,
  59. value: (prevState.value || 0) - 1,
  60. }));
  61. };
  62. return (
  63. <CounterPane color={color}>
  64. <h3>{label}</h3>
  65. <div>
  66. <button onClick={decrement} style={{ margin: "2px" }}>
  67. -
  68. </button>
  69. <label style={{ userSelect: "none" }}>
  70. <input
  71. style={{
  72. textColor,
  73. width: "2.5em",
  74. display: "block",
  75. textAlign: "center",
  76. border: "none",
  77. margin: "0.2em 0",
  78. padding: "0.2em 0",
  79. fontSize: fontSize + "px",
  80. userSelect: "none",
  81. }}
  82. onKeyUp={(e) => e.stopPropagation()}
  83. onKeyDown={(e) => e.stopPropagation()}
  84. value={value}
  85. onChange={setValue}
  86. />
  87. </label>
  88. <button onClick={increment} style={{ margin: "2px" }}>
  89. +
  90. </button>
  91. </div>
  92. </CounterPane>
  93. );
  94. };
  95. export default memo(Counter);