react props 简写

geekymv 发表于:2024-08-19 22:59:33 阅读数:375

<div id="test"></div>
        <div id="test2"></div>

        <script src="https://unpkg.com/react@16/umd/react.development.js"></script>
        <script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
        <!-- 引入 rop-types.js 用于对属性标签属性进行限制 -->
        <script src="https://unpkg.com/[email protected]/prop-types.js"></script>

        <!-- 引入 babel, 用于将 jsx 转为 js -->
        <!-- Don't use this in production: -->
        <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>

        <!-- 此处一定要写 babel -->
        <script type="text/babel">
            class Person extends React.Component {

                /* 对 props 进行限制 */
                static propTypes = {
                    name: PropTypes.string.isRequired,
                    age: PropTypes.number,
                    sex: PropTypes.string,

                }
                /* 设置默认值 */
                static defaultProps = {
                    sex: '未知',
                    age: 18
                }

                render() {
                    // props 是只读的
                    // this.props.age = 20

                    return (
                        <ul>
                            <li>姓名:{this.props.name}</li>
                            <li>年龄:{this.props.age}</li>
                            <li>性别:{this.props.sex}</li>
                        </ul>
                    )
                }
            }

            

            

            const p = {name:"jack", age:18}

            ReactDOM.render(<Person name="tony" age={20} sex="男"/>, document.getElementById('test'))

            /* 批量传递 props */
            ReactDOM.render(<Person {...p}/>, document.getElementById('test2'))

        </script>

Barbara Middleton
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis porta eros lacus, nec ultricies elit blandit non. Suspendisse pellentesque mauris sit amet dolor blandit rutrum. Nunc in tempus turpis.
Like · Reply · 3 hrs

Sean Brown
Donec sollicitudin urna eget eros malesuada sagittis. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Aliquam blandit nisl a nulla sagittis, a lobortis leo feugiat.
Like · Reply · 2 hrs

Vivamus quis semper metus, non tincidunt dolor. Vivamus in mi eu lorem cursus ullamcorper sit amet nec massa.
Morbi vitae diam et purus tincidunt porttitor vel vitae augue. Praesent malesuada metus sed pharetra euismod. Cras tellus odio, tincidunt iaculis diam non, porta aliquet tortor.

Kayli Eunice
Sed convallis scelerisque mauris, non pulvinar nunc mattis vel. Maecenas varius felis sit amet magna vestibulum euismod malesuada cursus libero. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Phasellus lacinia non nisl id feugiat.
Like · Reply · 2 hrs