V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
lblblong
V2EX  ›  React

React 大佬有没有, ts 有办法在编译阶段限制 react 子组件的参数类型吗

  •  
  •   lblblong · 2020-08-25 16:46:03 +08:00 · 1760 次点击
    这是一个创建于 1311 天前的主题,其中的信息可能已经有所发展或是发生改变。

    比如有一个 Form 组件,它需要所有子组件都有 name 字段

    <Form>
        <Input name="username"></Input>
        <Select name="sex"></Select>
        
        // 这里写的时候会报错,因为没有 name 字段
        <div></div>
    </Form>
    

    还有就是 form 可以限制子组件参数的类型,比如:

    interface IUserSchema {
        username: string
        sex: 1 | 2
    }
    
    <Form schema={IUserSchema}>
        <Input name="username"></Input>
        <Select name="sex"></Select>
        
        // 这里写的时候会报错,因为没有 age 字段
        <Input name="age"></Input>
    </Form>
    

    注意,以上都需要在编译阶段就过不了

    interface IProps {
      children?: // 这里的类型需要怎么写才能实现上面的需求呢? 
    }
    
    export const Form: FunctionComponent<IProps> = ({ children }) => {
      return <form>{children}</form>
    }
    
    5 条回复    2020-08-26 10:21:05 +08:00
    sunjourney
        1
    sunjourney  
       2020-08-25 17:09:57 +08:00
    不能
    shunia
        2
    shunia  
       2020-08-25 17:12:41 +08:00
    swirling
        3
    swirling  
       2020-08-25 17:17:29 +08:00
    你需要一个好一点的 form 库来做这件事
    KuroNekoFan
        4
    KuroNekoFan  
       2020-08-26 05:44:39 +08:00 via iPhone
    那你可能需要把 jsx 用一组数据来表示,再把这组数据 map 成 jsx 了
    lblblong
        5
    lblblong  
    OP
       2020-08-26 10:21:05 +08:00
    @shunia 我测试没有用欸,不知道是不是 tsconfig 配置的问题
    https://img.vim-cn.com/d5/990a67b42d42bca2ad5fb80bf8a653cf734147.png
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1129 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 22:56 · PVG 06:56 · LAX 15:56 · JFK 18:56
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.