美文网首页
使用ts和react创建一个函数组件

使用ts和react创建一个函数组件

作者: sweetBoy_9126 | 来源:发表于2020-04-17 16:19 被阅读0次

    创建

    yarn create react-app ts-react-demo --typescript
    

    写一个button组件

    1. 接受size属性
    • button.tsx
    import React from 'react'
    export default function() {
        return <div className="button">button</div>
    }
    
    • index.tsx
    import Button from './button'
    
    ReactDOM.render(
        <div>Hello World<Button></Button></div>, 
        document.getElementById('root')
    );
    

    让button支持size
    在使用button的时候传入一个size,然后我们需要在组件内部通过prop声明接受的这个size的类型

    • button.tsx
    interface Iprops {
        size?: string
    }
    export default function(Props: Iprops) {
        return <div className={`button ${Props.size}`}>button</div>
    }
    
    • index.tsx
    import Button from './button'
    
    ReactDOM.render(
        <div>
            <Button size="small"></Button>
            <Button></Button>
            <Button size="big"></Button>
        </div>, 
        document.getElementById('root')
    );
    
    1. 可以设置按钮内容

    我们现在直接在我们引用Button的时候里面写内容会报错,它说我们缺少children属性,所以我们就要在接口里添加一个children

    • button.tsx
    interface Iprops {
        size?: string,
        children?: string
    }
    export default function(Props: Iprops) {
        return <div className={`button ${Props.size}`}>{Props.children}</div>
    }
    

    我们还想让内容里面可以使用html标签

    它说不能把Element类型分配给string,所以我们要给children加一个Element类型

    interface Iprops {
        size?: string,
        children?: string | JSX.Element
    }
    

    让内容接受多个标签

    <Button size="small">
        <span>小改改</span>
        <span>你瞧瞧</span>
    </Button>
    
    children?: string | JSX.Element | JSX.Element[]
    

    问题:正常情况下每个组件都会有children,如果我们有多个组件的话,那么你每个里面都得写children,写起来就会很繁琐,那么我们怎么简化我们的代码那?
    解决办法:使用React的函数组件
    声明一个变量类型为React的函数组件然后把我们定义的接口作为类型传进去,react的函数组件会帮我声明一个children

    interface Iprops {
        size?: string
    }
    const Button: React.FunctionComponent<Iprops> = function(Props) {
        return <div className={`button ${Props.size}`}>{Props.children}</div>
    }
    export default Button
    
    支持点击事件
    interface Iprops {
        size?: string,
        onClick?: React.MouseEventHandler
    }
    const Button: React.FunctionComponent<Iprops> = function(Props) {
        return <div className={`button ${Props.size}`} onClick={Props.onClick}>{Props.children}</div>
    }
    

    相关文章

      网友评论

          本文标题:使用ts和react创建一个函数组件

          本文链接:https://www.haomeiwen.com/subject/rofdyctx.html