【react】props的批量传递
·
真实开发中,如果有很多个要传递的属性,并且属性值很有可能是通过后台接口拿到的,那么一个个的在标签上写属性就不行了
正确写法:
- 此处{ …p }的{}不是解构赋值的那个{},而是react用来放置变量的{},实际上真实的表达式只有…p,但是根据es6语法,对象的展开运算符必须要包一层{}的,这里是因为react.development.js和babel将代码转义了才可以这样写
- 这里的{ …p }绝对不是解构赋值的意思,而是单纯的使用了变量表达式p,他仅仅适用于标签属性的传递
const p = { name: "tom", sex: "girl", age: "18" }
// ReactDOM.render(<Person name={p.name} sex={p.sex} age={p.age} />, document.getElementById('test'))
ReactDOM.render(<Person { ...p } />, document.getElementById('test'))
完整代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>props的批量传递</title>
</head>
<body>
<div id="test"></div>
<script crossorigin src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script crossorigin src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script type="text/babel">
// 创建组件
class Person extends React.Component {
render () {
// render里面的this指向Person的实例对象,而实例对象上有一个属性props,可以用他来给组件传值
const { name, sex, age } = this.props
return (
<ul>
<li>姓名: { name }</li>
<li>性别: { sex }</li>
<li>年龄: { age }</li>
</ul>
)
}
}
/*
真实开发中,如果有很多个要传递的属性,并且属性值很有可能是通过后台接口拿到的,那么这样写就不行了
*/
const p = { name: "tom", sex: "girl", age: "18" }
// ReactDOM.render(<Person name={p.name} sex={p.sex} age={p.age} />, document.getElementById('test'))
ReactDOM.render(<Person { ...p } />, document.getElementById('test'))
// 此处{ ...p }的{}不是解构赋值的那个{},而是react用来放置变量的{},实际上真实的表达式只有...p,但是根据es6语法,对象的展开运算符必须要包一层{}的,这里是因为react.development.js和babel将代码转义了才可以这样写
// 这里的{ ...p }绝对不是解构赋值的意思,而是单纯的使用了变量表达式p,他仅仅适用于标签属性的传递
</script>
</body>
</html>
更多推荐
所有评论(0)