1、可以给组件传递任意类型的数据。
通过前面的案例,我们给组件传递了字符串和数值类型的数据。(注意:age={18}这种传递的方式为数值类型,如果是age='18'这种传递的方式为字符串类型)
在向类组件传递数据的时候,采用了如下的代码
ReactDom.render(<ShowMessage name={'zhangsan'} age={18} />,document.getElementById('root'))
对应的,可以在类组件中将传递过来的数据进行输出打印
class App extends React.Component{
render() {
console.log(this.props);//输出传递过来的数据,查看对应的类型
return (
<div>
<h1>我叫{this.props.name},今年{this.props.age}岁</h1>
</div>
)
}
}
export default App
通过上面的输出,可以在控制台上看出,传递过来的'name'属性的值是一个字符串,‘age’属性传递过来的值为数字。如果在进行传递的时候,采用了如下的写法
ReactDom.render(<ShowMessage name={'zhangsan'} age='18'/>,document.getElementById('root'))
那么传递到类组件中的age属性值的类型为字符串。
当然这里也可以传递'数组',如下代码所示:
import ShowMessage from './17、props基本使用.js'
ReactDom.render(<ShowMessage name={'zhangsan'} age='18' arr={['学习','睡觉']}/>,document.getElementById('root'))
下面在组件内部,对传递过来的arr数组进行遍历
import React, { Component } from "react";
class ControlComponent extends Component {
render() {
console.log(this.props);
return (
<div>
<h1>
我叫{this.props.name},年龄:{this.props.age},爱好:
{this.props.arr.map((item) => {
return <span key={item}>{item}</span>;
})}
</h1>
</div>
);
}
}
export default ControlComponent;
在上面的代码中,通过map对数组进行遍历,遍历的内容通过return进行返回
当然,也可以传递对应的’函数‘,如下代码所示:
import ShowMessage from './props基本使用.js'
ReactDom.render(<ShowMessage name={'zhangsan'} age='18' arr={['学习','睡觉']} fn={()=>{console.log('传递过来的是函数')}}/>,document.getElementById('root'))
既然,传递过来的是函数,那么在对应的组件中就可以执行该函数,如下代码所示:
class App extends React.Component{
render() {
console.log(this.props);//输出传递过来的数据,查看对应的类型
this.props.fn();//执行传递过来的函数。
return (
<div>
<h1>我叫{this.props.name},今年{this.props.age}岁</h1>
</div>
)
}
}
export default App
目录
2、props对象是只读的,只能读取其中的属性值,不能修改对应的属性值。
class App extends React.Component{
render() {
console.log(this.props);//输出传递过来的数据,查看对应的类型
this.props.fn();//执行传递过来的函数。
//尝试修改props中的属性值。(这里会出错)
this.props.name='lisi';
return (
<div>
<h1>我叫{this.props.name},今年{this.props.age}岁</h1>
</div>
)
}
}
export default App
在上面的代码中,尝试修改props对象中的name属性值时出现了错误。
3、在使用类组件的时候,如果写了构造函数,应该将props传递给super( ),否则在构造函数中无法获取到props.
class App extends React.Component{
constructor(){
super()
console.log(this.props);//这里输出的是undefined
}
render() {
// console.log(this.props);//输出传递过来的数据,查看对应的类型
// this.props.fn();//执行传递过来的函数。
//尝试修改props中的属性值。(这里会出错)
// this.props.name='lisi';
return (
<div>
<h1>我叫{this.props.name},今年{this.props.age}岁</h1>
</div>
)
}
}
export default App
在上面的代码中,在constructor构造方法中直接获取this.props,输出的结果为undefined. 但是在render中是可以获取到的。
现在将代码修改成如下的形式:
class App extends React.Component{
constructor(props){
super(props);
console.log(this.props);//现在这里可以获取到props中的内容
// 既然props通过构造函数传递过来了,所以这里可以省略this
console.log(props)
}
render() {
// console.log(this.props);//输出传递过来的数据,查看对应的类型
// this.props.fn();//执行传递过来的函数。
//尝试修改props中的属性值。(这里会出错)
// this.props.name='lisi';
return (
<div>
<h1>我叫{this.props.name},今年{this.props.age}岁</h1>
</div>
)
}
}
export default App
所以这里推荐使用这种方式:将props作为constructor构造函数的参数。
学IT,上博学谷