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'))
函数式组件与类组件的区别和使用,函数式组件比较简单,一般用于静态没有交互事件内容的组件页面。类组件,一般又称为动态组件,那么一般会有交互或者数据修改的操作。
最后
公众号:小何成长,佛系更文,都是自己曾经踩过的坑或者是学到的东西
有兴趣的小伙伴欢迎关注我哦,我是:
何小玍
。大家一起进步鸭最近有点忙,文章可能有点水,有问题大家可以关注我公众号,一起交流
注释都写到代码里面了,望见谅