A React Typescript Change Handler to Rule Them All

栏目: IT技术 · 发布时间: 4年前

内容简介:In React with Typescript, you may be tempted to roll individual change handlers for each field in a component. Today I’ll show you how to avoid this redundant work and write just one change handler!Here’s a simple use case: we have a form in React with two

In React with Typescript, you may be tempted to roll individual change handlers for each field in a component. Today I’ll show you how to avoid this redundant work and write just one change handler!

A Simple Use Case

Here’s a simple use case: we have a form in React with two text inputs and a checkbox input. These inputs will populate a User object, which will have the following types:

type User = {
  name: string;
  age: number;
  admin: boolean;
};

Let’s see how this might look in the context of a React component. We’ll use the useState hook to maintain internal state for the user object.

import React, { useState } from 'react';

type User = {
  name: string;
  age: number | null;
  admin: boolean;
};

const defaultUser: User = {
  name: '',
  age: null,
  admin: false,
};

function App() {
  const [user, setUser] = useState(defaultUser);

  return (
    <div>
      <input value={user.name} />
      <input value={user.age || ''} />
      <input type="checkbox" checked={user.admin} />
    </div>
  );
}

Handling Changes

But how to handle changes for each property? Well, we could create a different change handler for each input, but that would be redundant. Let’s create a single onUserChange that set’s the correct prop for each input.

import React, { useState } from 'react';

type User = {
  name: string;
  age: number | null;
  admin: boolean;
};

const defaultUser: User = {
  name: '',
  age: null,
  admin: false,
};

function App() {
  const [user, setUser] = useState(defaultUser);

  const onUserChange = <P extends keyof User>(prop: P, value: User[P]) => {
    setUser({ ...user, [prop]: value });
  };

  return (
    <div>
      <input
        value={user.name}
        onChange={e => {
          onUserChange('name', e.target.value);
        }}
      />
      <input
        value={user.age || ''}
        onChange={e => {
          onUserChange('age', parseInt(e.target.value));
        }}
      />
      <input
        type="checkbox"
        checked={user.admin}
        onChange={() => {
          onUserChange('admin', !user.admin);
        }}
      />
    </div>
  );
}

The secret sauce here is the generic we use in the onUserChange handler. By saying that prop is of type P where P extends keyof User , we can typecheck the second argument of onUserChange based on the first argument. Then, when we setUser , the typescript compiler is happy with our typings.


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

信息乌托邦

信息乌托邦

桑斯坦 / 毕竞悦 / 法律出版社 / 2008-10-1 / 28.50元

我们被无限的媒体网从四面包围,如何能够确保最准确的信息脱颖而出、并且引起注意?在本书中,凯斯•R. 桑斯坦对于积蓄信息和运用知识改善我们生活的人类潜能,展示了深刻的乐观理解。 在一个信息超负荷的时代里,很容易退回到我们自己的偏见。人群很快就会变为暴徒。伊拉克战争的合法理由、安然破产、哥伦比亚号航天载人飞机的爆炸——所有这些都源自埋于“信息茧房”的领导和组织做出的决定,以他们的先入之见躲避意见......一起来看看 《信息乌托邦》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具