React(十二):props的函数组件中使用

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>props的函数组件实现</title>
    <script src="https://unpkg.com/react@18/umd/react.development.js"></script>
    <script src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script>

    <!-- Don't use this in production: -->
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

    <!-- prop类型限制导入 -->
    <script src="https://unpkg.com/prop-types@15.6/prop-types.js"></script>

</head>

<body>

    <div id="test1"></div>
    <div id="test2"></div>
    <div id="test3"></div>

</body>

<script type="text/babel">
    function Person(props) {
        const { name, sex, age } = props
        return (
            <ul>
                <li>姓名:{name}</li>
                <li>性别:{sex}</li>
                <li>年龄:{age}</li>
            </ul>
        )
    }

    //props类型限制
    Person.propTypes = {
        name: PropTypes.string.isRequired,//是字符串类型且不能为空
        sex: PropTypes.string,//是字符串类型
        age: PropTypes.number,//是数值类型
        speak: PropTypes.func//是函数类型
    }
    //props默认值
    Person.defaultProps = {
        age: 0,
        sex: '未知'
    }

    //基本使用
    ReactDOM.render(<Person name="张三" age={15} sex="" />, document.getElementById('test1'))
    ReactDOM.render(<Person name="李四" />, document.getElementById('test2'))

    //批量传递props
    const p = { name: "王五", age: 17, sex: "", speak: function a() { } }
    ReactDOM.render(<Person {...p} />, document.getElementById('test3'))

</script>

</html>

 

posted @ 2023-07-30 19:41  谁知道水烫不烫  阅读(18)  评论(0编辑  收藏  举报