面试题答案
一键面试- 定义
Form
组件接收的props
类型:- 首先定义各种表单字段的公共属性接口:
interface CommonFieldProps { id: string; label: string; }
- 然后分别定义不同类型表单字段的特有属性接口:
- 文本输入框:
interface TextInputFieldProps extends CommonFieldProps { type: 'text'; // 可以添加更多文本输入框特有的属性,比如 placeholder 等 placeholder?: string; }
- 下拉框:
interface SelectFieldProps extends CommonFieldProps { type:'select'; options: { label: string; value: string | number }[]; }
- 单选框:
interface RadioFieldProps extends CommonFieldProps { type: 'radio'; options: { label: string; value: string | number }[]; }
- 接着使用联合类型定义所有可能的表单字段类型:
type FormFieldProps = TextInputFieldProps | SelectFieldProps | RadioFieldProps;
- 最后定义
Form
组件的props
类型,fields
属性为表单字段配置数组:
interface FormProps { fields: FormFieldProps[]; }
- 编写
Form
组件的渲染逻辑:- 在
Form
组件中,通过遍历fields
数组来渲染不同类型的表单字段。
import React from'react'; const Form: React.FC<FormProps> = ({ fields }) => { return ( <form> {fields.map(field => { switch (field.type) { case 'text': return ( <div key={field.id}> <label htmlFor={field.id}>{field.label}</label> <input type={field.type} id={field.id} placeholder={field.placeholder} /> </div> ); case'select': return ( <div key={field.id}> <label htmlFor={field.id}>{field.label}</label> <select id={field.id}> {field.options.map(option => ( <option key={option.value} value={option.value}>{option.label}</option> ))} </select> </div> ); case 'radio': return ( <div key={field.id}> <label>{field.label}</label> {field.options.map(option => ( <div key={option.value}> <input type="radio" id={`${field.id}-${option.value}`} value={option.value} /> <label htmlFor={`${field.id}-${option.value}`}>{option.label}</label> </div> ))} </div> ); default: return null; } })} </form> ); }; export default Form;
- 在上述渲染逻辑中,通过
switch
语句根据field.type
的值来决定渲染哪种类型的表单字段,这样就能根据不同的表单字段配置,类型安全地渲染出相应的表单元素。
- 在