<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">
/* 函数式组件使用 props */
function Person(props) {
const {name, age, sex} = props
return (
<ul>
<li>姓名:{name}</li>
<li>年龄:{age}</li>
<li>性别:{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 23:00:24 阅读数:178