React 小知识 - 类型限制

354 阅读1分钟

针对组件之间传值,在 vue 中,可以直接限制 props 的类型

Vue.component("MyComponent", {
    props: {
        propA: Number, 
        propB: [String,Number], // 多个可能的而类型
        propC: { // 必填字符串
            type: String,
            required: true
        }
   }
}

而在 react 中,则需借助第三方库 prop-types

// yarn add prop-types
// npm i prop-types -D

// 这是一个 todo 案例中的某个组件代码片段
import React, { Component } from 'react'
import PropTypes from 'prop-types'

import Item from '../Item'

export default class List extends Component {
    
    // handleChange 是一个必须的函数
    // todos 是一个必须的数组
    static propTypes = {
        handleChange:PropTypes.func.isRequired,
        todos:PropTypes.array.isRequired
    }

    render() {
        const {todos,handleChange} = this.props;
        return (
            <ul className="list-container">
                {todos.map(todo=>{
                    return <Item {...todo} key={todo.id} handleChange={handleChange}/>
                })}
            </ul>
        )
    }
}

推荐一个实用的随机生成唯一字符串库 nanoid

//yarn add nanoid
//or
//npm i nanoid -D

// 使用方法
nanoid() // 随机生成 PpC_cj3BARAO1LKgokGN7