React 组件支持
函数式组件与类组件的区别和使用,函数式组件比较简单,一般用于静态没有交互事件内容的组件页面。类组件,一般称为动态组件,那么一般会有交互或者数据修改的操作。
1 函数式组件:
function Childcom (props) {
console.log(props);
let weather = props.weather
let title = <h2>我是副标题</h2>
return (
<div>
<h1>函数式组件</h1>
{title}
<span>{weather==="下雨" ? "不出门" : "出门"}</span>
</div>
)
}
2 类组件:
class HelloWorld extends React.Component{
render(){
console.log(this);
return (
<div>
<h1>类组件定义的HelloWorld</h1>
<Childcom weather={this.props.weather}/>
</div>
)
}
}
ReactDOM.render(
<HelloWorld weather='出太阳'/>,
document.getElementById('root')
)
3 复合组件:组件中有其他组件 如上
React State
相当于vue的data,但是使用方式和vue不一致
class Clock extends React.Component{
constructor (props) {
super(props)
// 构造函数初始化数据
this.state = {
time: new Date().toLocaleTimeString()
}
}
render(){
return (
<div>
<h1>当前时间:{this.state.time}</h1>
</div>
)
}
// 生命周期函数,渲染组件完成时的函数
componentDidMount(){
setInterval(() => {
// 修改数据 调用setState 切勿直接修改数据
// 通过 setState 修改完的数据 并不会立即修改Dom里面的内容,react会在这个函数所有设置的状态改变后统一对比虚拟DOM对象,然后统一修改,提升性能
this.setState({
time:new Date().toLocaleTimeString()
})
},1000)
}
}
/* react 重复渲染一个组件时 其构造函数不会重复调用,渲染函数会重复调用 */
ReactDOM.render(
<Clock/>,
document.getElementById('root')
)