【问题标题】:Create a reusable Form Input component with React & TypeScript使用 React 和 TypeScript 创建可重用的表单输入组件
【发布时间】:2022-08-18 16:25:06
【问题描述】:

如何在打字稿中定义输入属性?我有一个 AddUser 组件和 TextInput 组件,我想在 AddUser 组件中导入 TextInput 组件,然后将 props 传递给 TextInput 组件。

添加用户.tsx

import Button from \'../Shared/Form/Button/Button\';
import Form from \'../Shared/Form/Form\';
import TextArea from \'../Shared/Form/TextArea/TextArea\';
import TextInput from \'../Shared/Form/TextInput/TextInput\';

const AddUser = () => {
    return (
        <div>
            <h1>Add User</h1>
            <Form method=\"post\" className={\'user-form\'}>
                <TextInput label={\'Name\'} type=\"text\" name=\"name\" required />
                <TextInput label={\'Email\'} type=\"email\" name=\"email\" required />
                <TextInput label={\'Country\'} type=\"text\" name=\"country\" required />
                <TextInput label={\'Phone\'} type=\"text\" name=\"phone\" required />
                <TextArea label={\'Address\'} name=\"address\" cols=\"30\" rows=\"4\" />
                <div className=\"form-button\">
                    <Button type={\'submit\'} className={\'btn-add\'}>
                        Add
                    </Button>
                    <Button type={\'submit\'} className={\'btn-close\'}>
                        Cancel
                    </Button>
                </div>
            </Form>
        </div>
    );
};

export default AddUser;

文本输入.tsx

const TextInput = ({ className, label, ...rest }: { className: string; label: string }) => {
    return (
        <div className={`${className} form-field`}>
            <label htmlFor={label}>{label}</label>
            <input {...rest} />
        </div>
    );
};

export default TextInput;

    标签: javascript reactjs typescript


    【解决方案1】:

    你可以扩展 HTMLProps,它带有 react:

    import { HTMLProps } from "react";
    
    interface MyCOmponentProps extends HTMLProps<HTMLInputElement> {
      {...}
    }
    

    【讨论】:

      猜你喜欢
      • 2021-08-30
      • 2020-12-02
      • 2018-11-19
      • 2021-04-30
      • 2019-09-09
      • 2014-11-20
      • 2020-10-13
      • 2022-11-29
      • 2022-12-20
      相关资源
      最近更新 更多