<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>
react props 简写
geekymv 发表于:2024-08-19 22:59:33 阅读数:375