目录
1 传递数据时,可以传递任意类型的数据
2 props是只读的对象,不能修改传过来对象的属性值
3??使用类组件时,如果写了构造函数,应该将props传递给super(),否则无法在构造函数中获取到props
props的特点
1 传递数据时,可以传递任意类型的数据
(比如传递字符串、数字、数组、函数、JSL表达式)
?? ?字符串: 属性加引号表示传递的是字符串类型 ?? ?数字: {数字}表示传递的是数字类型 ?? ?数组: {[]}可以传递数组 ?? ?函数: {()=>{}} ?? ?JSL表达式: {<p>这是jsl表达式</p>}
代码
import React from "react";
import ReactDOM from "react-dom";
class Hello extends React.Component {
//2 接收数据
render() {
console.log(this.props)
//调用函数
this.props.fn();
//解构数组:其他名字
const [name1,name2,name3]=this.props.nameOther
return (
<div>
<h1>name:{this.props.name}</h1>
<h1>age:{this.props.age}</h1>
<h1>其他名字:{name1},{name2},{name3}</h1>
{this.props.tag}
</div>
)
}
}
//1 传递数据
ReactDOM.render(<Hello
name='妹妹'
age={3}
nameOther={["小糯米", "小狗狗", "婵妹妹"]}
fn={()=> console.log("这是一个函数")}
tag={<p>这是jsl表达式</p>}
/>, document.getElementById("root"));
效果

?控制台

?
2 props是只读的对象,不能修改传过来对象的属性值

?报错如下

3??使用类组件时,如果写了构造函数,应该将props传递给super(), 否则无法在构造函数中获取到props

?没有将props传递给构造函数的super(), 控制台获取不到对象

?修改:?将props传递给构造函数的super()

?可以获取到props对象了

constructor(props){
super(props)
console.log(props)
//console.log(this.props)
}
|