好客租房49-组件的props(特点)

特点
1可以给组件传递任意类型的数据

2props是只读的对象 只能读取属性的值 无法修改对象

3注意:使用类组件时 如果写了构造函数 应该将props传递给super() 否则 无法在构造函数

中获取到props

//导入react
import React from 'react'
import ReactDOM from 'react-dom'
 
//导入组件
// 约定1:类组件必须以大写字母开头
// 约定2:类组件应该继承react.component父类 从中可以使用父类的方法和属性
// 约定3:组件必须提供render方法
// 约定4:render方法必须有返回值
 
class HelloWorld extends React.Component {
    render() {
        console.log(this.props)
        return (
            <div>
                <h1>props:{this.props.name}</h1>
            </div>
        )
    }
}
//函数组件
// const HelloWorld = (props) => {
//     console.log(props)
//     return (
//         <div>
//             <h1>props:{props.name}</h1>
//         </div>
//     )
// }
 
ReactDOM.render(
    <HelloWorld name="geyao" color={['red', 'blue']}
    tags={<p>哈哈哈</p>} />,
    document.getElementById('root')
)
//导入react
import React from 'react'
import ReactDOM from 'react-dom'
 
//导入组件
// 约定1:类组件必须以大写字母开头
// 约定2:类组件应该继承react.component父类 从中可以使用父类的方法和属性
// 约定3:组件必须提供render方法
// 约定4:render方法必须有返回值
 
class HelloWorld extends React.Component {
    constructor(props){
        super(props)
        //constructor中拿不到props
        console.log(props)
    }
    render() {
        console.log(this.props)
        return (
            <div>
                <h1>props:{this.props.name}</h1>
            </div>
        )
    }
}
//函数组件
// const HelloWorld = (props) => {
//     console.log(props)
//     return (
//         <div>
//             <h1>props:{props.name}</h1>
//         </div>
//     )
// }
 
ReactDOM.render(
    <HelloWorld name="geyao" color={['red', 'blue']}
    tags={<p>哈哈哈</p>} />,
    document.getElementById('root')

posted @   前端导师歌谣  阅读(37)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
点击右上角即可分享
微信分享提示