内容简介: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.
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
社群营销实战手册
秋叶、邻三月、秦阳 / 人民邮电出版社 / 2018-1 / 69.00元
互联网正从“物以类聚”,走向“人以群分”的时代。秋叶等人的“社群营销”,并非单纯靠社群卖东西,而是建立一种中心化的、自行运转的生态,让“同好”们形成紧密的联系,创造出海量营销机会。 《社群营销实战手册 从社群运营到社群经济》共5章内容,从社群的定位、建立、扩张、变现、运营,到社群的生命周期延长、社群运营团队的打造和管理以及社群管理工具,大量干货秘笈一应俱全,并提供丰富的运营实战案例,全面解读社群的......一起来看看 《社群营销实战手册》 这本书的介绍吧!
MD5 加密
MD5 加密工具
HEX HSV 转换工具
HEX HSV 互换工具