react 组件props属性

时间:2020-05-01
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

<div id="test">

</div>

<script src="js/react.development.js"></script>
<script src="js/react-dom.development.js"></script>
<script src="js/babel.min.js"></script>
<script src="js/prop-types.js"></script>

<script type="text/babel">
    // 创建组件
    class PersonConponent extends React.Component {
        constructor(props) {
            super(props);
        }

        render() {
            return (
                <div>
                    <h1>{this.props.name}</h1>
                    <h1>{this.props.age}</h1>
                    <h1>{this.props.sex}</h1>
                </div>
            );
        }
    }

    // props 默认值
    PersonConponent.defaultProps = {
        age: 18,
        sex: '男'
    };

    // props 类型限制
    PersonConponent.propTypes = {
        name: PropTypes.string.isRequired,
        sex:PropTypes.string.isRequired,
        age:PropTypes.number.isRequired
    };

    let info = {
        name: 'wyzda',
        age: '28',
        sex: '女'
    };
    // 渲染虚拟dom
    //ReactDOM.render(<PersonConponent name={info.name} age={info.age} sex={info.sex}/>, document.getElementById('test'));
    //ReactDOM.render(<PersonConponent {...info}/>, document.getElementById('test'));
    ReactDOM.render(<PersonConponent name={info.name} age={info.age}/>, document.getElementById('test'));
</script>
</body>
</html>