React + TypeScript 实践
import React, { useState } from 'react';
import { Button, TextField } from '@fluentui/react';
interface IFormValues {
name: string;
email: string;
}
const initialFormValues: IFormValues = {
name: '',
email: ''
};
const RegistrationForm: React.FC = () => {
const [formValues, setFormValues] = useState(initialFormValues);
const handleChange = (event: React.FormEvent<HTMLInputElement>) => {
const { name, value } = event.currentTarget;
setFormValues({ ...formValues, [name]: value });
};
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
console.log(formValues);
};
return (
<form onSubmit={handleSubmit}>
<TextField
label="Name"
name="name"
value={formValues.name}
onChange={handleChange}
/>
<TextField
label="Email"
name="email"
type="email"
value={formValues.email}
onChange={handleChange}
/>
<Button type="submit">Submit</Button>
</form>
);
};
export default RegistrationForm;
这个代码实例展示了如何在React组件中使用TypeScript和Fluent UI控件创建一个简单的注册表单。它使用了useState
钩子来管理表单输入的状态,并且包含了表单的变更处理函数和提交处理函数。这个实例为开发者提供了一个学习和实践React和TypeScript结合使用的好例子。
评论已关闭