<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Title</title></head><body><div id="example1"></div><hr><div id="example2"></div><script type="text/javascript" src="../js/react.development.js"></script><script type="text/javascript" src="../js/react-dom.development.js"></script><script type="text/javascript" src="../js/prop-types.js"></script><script type="text/javascript" src="../js/babel.min.js"></script> <script type="text/babel"> /* * 需求:自定义用来显示一个人员信息的组件,效果如页面.说明: 1.如果性别没有指定,默认为男 2.如果年龄没有指定,默认为18 * */ //1.定义组件 (简单) /*function Person(props) { return ( <ul> <li>姓名:{props.name}</li> <li>年龄:{props.age}</li> <li>性别:{props.sex}</li> </ul> ) }*/ //1.定义组件(复杂) class Person extends React.Component { render() { console.log(this); return ( <ul> <li>姓名:{this.props.name}</li> <li>年龄:{this.props.age}</li> <li>性别:{this.props.sex}</li> </ul> ) } } //指定属性默认值 Person.defaultProps = { sex: ‘男‘, age: 18 }; //指定属性值的类型和必要性 Person.propTypes = { name: PropTypes.string.isRequired, sex: PropTypes.string, age: PropTypes.number }; //2.渲染组件标签 const person = { name: ‘Tom‘, age: 18, sex: ‘女‘ }; /* * ...的作用 * 1.打包 * function fn(...as) {} fn(1, 2, 3) * 2.解包 * const arr1 = [1, 2, 3] const arr2 = [6, ...arr1, 9] * */ ReactDOM.render(<Person {...person}/>, document.getElementById(‘example1‘)); const person2 = { myName: ‘Jack‘, age: 17 }; ReactDOM.render(<Person name={person2.myName} age={person2.age}/>, document.getElementById(‘example2‘));</script> </body></html>
原文地址:https://www.cnblogs.com/zhanzhuang/p/10704523.html
时间: 2024-11-01 16:13:01