Element V.S. Component·元素与组件
元素与组件
const div = React.createElement( 'div ' ,...)这是一个 React元素(d小写)
const Div = ()=>React.createElement( 'div'..)这是一个 React组件(D大写)
·什么是组件
1、能跟其他物件组合起来的物件,就是组件
2.组件并没有明确的定义,靠感觉理解就行
3.就目前而言,一个返回 React元素的函数就是组件
4.在 Vue里,一个构造选项就可以表示一个组件
React两种组件
React两种组件
一、函数组件
function welcome( props){
return <h1>Hello, {props.name}</h1>;
}
使用方法:<welcome name="frank"/>
二、类组件
class welcome extends React.Component {
render() {
return <h1>Hello,{this.props.name}< /h1>
}
}
使用方法:<Welcome name="frank " />
<Welcome /> 会被翻译成什么
< div / >会被翻译为React.createElement('div')
< Welcome/>翻译为React.createElement(Welcome)
可以用babel online直接翻译给你看
React.createElement的逻辑
1.如果传入一个字符串'div',则会创建一个div
2.如果传入一个函数,则会调用该函数,获取其返回值
3.如果传入一个类,则在类前面加个new(这会导致执行constructor),获取一个组件对象,然后调用对象的render方法,获取其返回值
添加props(外部数据)
1.类组件直接读取属性this.props.xxx
<Son s='nihao'></Son>
<div className="sun">{ this.props.s} 儿子</div>
2.函数组件直接读取参数props.xxX
<div className="sun">{props.s} 孙子</div>
添加state(内部数据)
1.类组件用this.state读,this.setState写
this.state={n:0}
this.setState({n : this.state.n+1})
或者
this.setState((state)=>{
const n = this.state.n+1
return {n}
})
2.函数组件用useState返回数组,第一项读,第二项写
const [n,setN]=React.useState(0)
小试牛刀
简单使用函数组件和类组件
import React from "react";
import './index.css'
const App =()=>{
return (
<div className="body">父组件
<Son></Son>
</div>
)
}
const Sun =()=>{
const [n,setN]=React.useState(0)
return (
<div className="sun">孙子n:{n}
<button onClick={()=>
setN(n+1)
}>+1</button>
</div>
)
}
class Son extends React.Component {
constructor(){
super()
this.state={
n:0
}
}
add(){
this.setState({n : this.state.n+1})
}
render(){
return (
<div className="son">儿子{this.state.n}
<button onClick={()=>this.add()}>+1</button>
<Sun></Sun>
</div>
)
}
}
export default App