美文网首页
react入门lesson3之props

react入门lesson3之props

作者: 江江简书 | 来源:发表于2020-04-08 20:54 被阅读0次
前言:这个props可以理解成属性,是通过html标签属性传递的,同时简单了解打包和解包的实现

实现props传递属性

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <div id="exam"></div>
    <div id="exam1"></div>
</body>
<script type="text/javascript" src="../react.development.js"></script>
<script type="text/javascript" src="../react-dom.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prop-types/15.6.0/prop-types.min.js"></script>
<script type="text/javascript" src="../babel.min.js"></script>
<script type="text/babel">
    //1.定义组织
    function Person(props) {
            return <ul>
                <li>{props.name}</li>
                <li>{props.age}</li>
                <li>{props.addr}</li>
            </ul>
    }

    //设定默认值
    Person.defaultProps = {
        name:'小明',
        age:19,
    }
    //设定默认类型
    Person.PropsTypes = {
        name:PropTypes.string.isRequired,
        age:PropTypes.number
    }
    let p1 = {
        name:'小李',
        age:18,
        addr:'广东',
    }
    let p2 = {
        age:16,
    }
    //2.渲染组件
    ReactDOM.render(<Person {...p1} />,document.getElementById('exam'))
    ReactDOM.render(<Person {...p2} />,document.getElementById('exam1'))
</script>
</html>

解包和打包

  • {...name} => 此方法就是将对象的值分别解包赋值
  • function(...args) =>此方法是可以传递多个参数同时打包成数组

相关文章

网友评论

      本文标题:react入门lesson3之props

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