<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 {
render() {
console.log(this)
return (
<ul>
<li>姓名:{this.props.name}</li>
<li>年龄:{this.props.age}</li>
<li>性别:{this.props.sex}</li>
</ul>
)
}
}
/* 对 props 进行限制 */
Person.propTypes = {
name: PropTypes.string.isRequired,
age: PropTypes.number,
sex: PropTypes.string,
}
/* 设置默认值 */
Person.defaultProps = {
sex: '未知',
age: 18
}
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:58:53 阅读数:366