Input 最佳实践

多个 Input输入

  1. function App() {
  2. const [state, setState] = useState({})
  3. const handleInputChange = (field) => {
  4. return (e) => {
  5. setUser((prevState) => ({
  6. ...prevState,
  7. [field]: e.target.value
  8. }));
  9. };
  10. };
  11. return (
  12. <Input
  13. value={state.name}
  14. onChagne={handleInputChange("name")}
  15. />
  16. )
  17. }

多个组件类型

策略模式,优化 if else逻辑

  1. import {
  2. VipAccount,
  3. AdminAccount,
  4. ModeratorAccount
  5. } from './component';
  6. const ACCOUNTS_MAP = {
  7. 'vip': VipAccount,
  8. 'admin': AdminAccount,
  9. 'moderator': ModeratorAccount,
  10. }
  11. function App({ type }) {
  12. const Component = ACCOUNTS_MAP[type]
  13. return (<Component />)
  14. }

ToDoList

  1. const DEFAULT_ITEMS = [
  2. 1, 2, 3, 4, 5
  3. ]
  4. function toggleArrayItem (arr, val) {
  5. return arr.includes(val)
  6. ? arr.filter(el => el !== val)
  7. : [...arr, val];
  8. }
  9. function useItemsList() {
  10. const [items, setItems] = useState(DEFAULT_ITEMS)
  11. const handleToggleItem = (num) => {
  12. return () => {
  13. setItems(toggleArrayItem(items, num))
  14. }
  15. }
  16. return {
  17. items,
  18. handleToggleItem,
  19. }
  20. }

image.png

金额输入

image.png

多币种
image.png