demo1 - 函数式组件
//函数式组件
function Childcom() {
let title = <h2>我是副标题</h2>
let weather = "下雨";
let isGo = weather === "下雨" ? "不出门" : "出门";
return (
<div>
<h1>函数式组件 hello world!</h1>
{title}
<div>
是否出门?
<span>{isGo}</span>
</div>
</div>
)
}
ReactDOM.render(<Childcom />, document.querySelector("#root"));
demo2 - 类组件
//类组件
class HelloWorld extends React.Component {
render() {
return (
<div>
类组件 Hello World!
</div>
)
}
}
ReactDOM.render(<HelloWorld />, document.querySelector("#root"));
demo3 - 函数式组件传参
function Childcom(props) {
console.log(props);
let weather = props.weather;
let isGo = weather === "下雨" ? "不出门" : "出门";
return (
<div>
<h1>函数式组件 hello world!</h1>
<div>
是否出门?
<span>{isGo}</span>
</div>
</div>
)
}
ReactDOM.render(<Childcom weather = "下雨"/>, document.querySelector("#root"));
组件里面套组件 - 复合组件
class HelloWorld extends React.Component {
render() {
return (
<div>
类组件 Hello World!
<Childcom weather = "下雨"/>
</div>
)
}
}
ReactDOM.render(<HelloWorld />, document.querySelector("#root"));
总结
函数式与类组件的区别和使用
- 函数式组件比较简单,一般用于静态没有交互事件内容的组件页面
- 类组件,一般又称为动态组件,那么一般会有交互或者数据修改的操作
- 组件中又有组件叫做复合组件,复合组件中既可以有类组件又可以有函数组件
- 函数式组件可以实现的功能,类一般能实现,类能实现的功能,函数式组件不一定能实现
网友评论