V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
lblblong
V2EX  ›  React

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

  •  
  •   lblblong · Aug 25, 2020 · 2590 views
    This topic created in 2073 days ago, the information mentioned may be changed or developed.

    比如有一个 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 replies    2020-08-26 10:21:05 +08:00
    sunjourney
        1
    sunjourney  
       Aug 25, 2020
    不能
    shunia
        2
    shunia  
       Aug 25, 2020
    swirling
        3
    swirling  
       Aug 25, 2020
    你需要一个好一点的 form 库来做这件事
    KuroNekoFan
        4
    KuroNekoFan  
       Aug 26, 2020 via iPhone
    那你可能需要把 jsx 用一组数据来表示,再把这组数据 map 成 jsx 了
    lblblong
        5
    lblblong  
    OP
       Aug 26, 2020
    @shunia 我测试没有用欸,不知道是不是 tsconfig 配置的问题
    https://img.vim-cn.com/d5/990a67b42d42bca2ad5fb80bf8a653cf734147.png
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5703 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 47ms · UTC 06:15 · PVG 14:15 · LAX 23:15 · JFK 02:15
    ♥ Do have faith in what you're doing.