网站首页 > 基础教程 正文
1、函数式组件
方法体首字母需要大写, 并且执行的时候,需要写< />
import React from 'react'
import ReactDOM from 'react-dom'
// 函数式组件
function Childcom() {
const title = <h2>我是副标题</h2>
const weather = '下雨'
// 条件判断
const isGo = weather == '下雨' ? '不出门' : '出门'
return (
<div>
<h1>函数式组件Hello World</h1>
<h3>{ title }</h3>
<span>是否出门? { isGo } </span>
</div>
)
}
ReactDOM.render(<Childcom />, document.getElementById('root'))
函数式组件传参
// 函数式组件
function Childcom(props) {
const title = <h2>我是副标题</h2>
// 条件判断
const isGo = props.weather == '下雨' ? '不出门' : '出门'
return (
<div>
<h1>函数式组件Hello World</h1>
{ title }
<span>是否出门? { isGo } </span>
</div>
)
}
ReactDOM.render(<Childcom weather="下雨" />, document.getElementById('root'))
2、类组件
// 类组件
// HelloWorld组件继承于react的componet对象
class HelloWorld extends React.Component {
render() {
return (
<div>
<h1>类组件定义Hello World</h1>
</div>
)
}
}
ReactDOM.render(<HelloWorld />, document.getElementById('root'))
3、函数式组件搭配类组件
复合组件,组件中又有其他的组件 可以有函数式组件,也可以有类组件
(在ReactDom里面,只能有一个根组件)
import React from 'react'
import ReactDOM from 'react-dom'
// 函数式组件
function Childcom(props) {
console.log(props)
const title = <h2>我是副标题</h2>
// 条件判断
const isGo = props.weather == '下雨' ? '不出门' : '出门'
return (
<div>
<h1>函数式组件Hello World</h1>
{ title }
<span>是否出门? { isGo } </span>
</div>
)
}
// 类组件
// HelloWorld组件继承于react的componet对象
class HelloWorld extends React.Component {
constructor(props) {
super(props)
this.state = {}
}
render() {
return (
<div>
<h1>类组件定义Hello World</h1>
<Childcom weather={ this.props.name } />
</div>
)
}
}
ReactDOM.render(<HelloWorld name="下雨" />, document.getElementById('root'))
函数式组件与类组件的区别和使用,函数式组件比较简单,一般用于静态没有交互事件内容的组件页面。类组件,一般又称为动态组件,那么一般会有交互或者数据修改的操作。
最后
公众号:小何成长,佛系更文,都是自己曾经踩过的坑或者是学到的东西
有兴趣的小伙伴欢迎关注我哦,我是:何小玍。大家一起进步鸭
最近有点忙,文章可能有点水,有问题大家可以关注我公众号,一起交流
注释都写到代码里面了,望见谅
- 上一篇: React学习笔记:创建组件
- 下一篇: React组件开发中常见的陷阱及解决
猜你喜欢
- 2024-11-21 广州蓝景分享—16个非常有用的React组件库,前端开发必备
- 2024-11-21 03 React组件(Component)
- 2024-11-21 如何设计更优雅的 React 组件?
- 2024-11-21 React 也就这么回事 05 —— 组件 & Props
- 2024-11-21 2022年前端React的100道面试题的第7题:组件的constructor
- 2024-11-21 前端开发react框架 - 组件
- 2024-11-21 React-组件的两种创建方式
- 2024-11-21 放弃 React 改用 Web 组件,微软这次重构让开发者不解:没有任何意义
- 2024-11-21 React系列十 - 高阶组件以及组件补充
- 2024-11-21 具有排序、筛选、分组、虚拟化、编辑功能的React表格组件
- 最近发表
- 标签列表
-
- gitpush (61)
- pythonif (68)
- location.href (57)
- tail-f (57)
- pythonifelse (59)
- deletesql (62)
- c++模板 (62)
- css3动画 (57)
- c#event (59)
- linuxgzip (68)
- 字符串连接 (73)
- nginx配置文件详解 (61)
- html标签 (69)
- c++初始化列表 (64)
- exec命令 (59)
- canvasfilltext (58)
- mysqlinnodbmyisam区别 (63)
- arraylistadd (66)
- node教程 (59)
- console.table (62)
- c++time_t (58)
- phpcookie (58)
- mysqldatesub函数 (63)
- window10java环境变量设置 (66)
- c++虚函数和纯虚函数的区别 (66)