react的render函數(shù)
很多時(shí)候我們都認(rèn)為react就是render大法,也確實(shí)是,每次我們都是通過(guò)render來(lái)重新渲染頁(yè)面,我們來(lái)看render的例子:
render() {
//JSX 語(yǔ)法
// {}
let helloWorld = 'yuxi';
// array
return (
<span>
<div className="App">
helloWorld,{helloWorld};
</div>
<div>
<States disable={false}
handShow={this.handShow}>
<span>hello world</span>
<span>hello yuxi</span>
<span>hello xiaoyu</span>
</States>
</div>
</span>
);
}
需要注意的是:render應(yīng)該只做頁(yè)面展示和渲染,不應(yīng)該有構(gòu)造函數(shù),回調(diào)函數(shù),聲明周期等。
react的state狀態(tài)
state是react的狀態(tài)管理,react是單向數(shù)據(jù)流的,當(dāng)我們需要對(duì)數(shù)據(jù)做改變的時(shí)候應(yīng)該是:
constructor() {
super();
console.log('this is constructor....')
this.state = {
disable:false,
}
}
handClick = () => this.setState(
{
disable: !this.state.disable
}
)
react的props屬性
當(dāng)我們需要把父組件的數(shù)據(jù)或者函數(shù)傳遞給子組件的時(shí)候,我們一般都使用props,我們來(lái)看一個(gè)例子:
傳遞給子組件:
<States disable={false}
handShow={this.handShow}>
<span>hello world</span>
<span>hello yuxi</span>
<span>hello xiaoyu</span>
</States>
子組件獲取:
let args = this.props.disable;
我們?cè)賮?lái)比較一下react和props,到底什么時(shí)候用哪個(gè)呢?
簡(jiǎn)單來(lái)理解:
- 如果需要改變數(shù)據(jù)就使用:
state - 如果需要傳遞數(shù)據(jù)就使用:
props
有一篇文章寫(xiě)得比較好:ReactJS: Props vs. State
react的聲明周期
react常用的聲明周期有:
- constructor 構(gòu)造函數(shù)
- componentWillMount
- componentDidMount
- componentWillUpdate
- componentDidUpdate
- componentWillUnmount
總的來(lái)說(shuō)我們常用的就是:
constructor,componentWillMount,componentDidMount
來(lái)看一個(gè)簡(jiǎn)單例子:
import React, { Component } from 'react'
export class States extends Component {
constructor() {
super();
console.log('this is constructor....')
this.state = {
disable:false,
}
}
handClick = () => this.setState(
{
disable: !this.state.disable
}
)
componentWillMount() {
console.log('this is will mount')
}
componentDidMount() {
console.log('this is did mount');
}
componentWillUpdate() {
console.log('this is will update');
}
componentDidUpdate() {
console.log('this is did update');
}
handShow = () => {
let args = this.state.disable;
this.props.handShow(args);
}
handFocus = () => {
this.refs.myFocus.focus();
}
render() {
// state practise
// set this.props.children
// operate virtral DOM
let args = this.props.children;
let DOME = React.Children.map(args,(child) => {
return <li>{child}</li>
});
console.log(DOME)
return (
<div>
<input type="text" disabled={this.state.disable}></input>
<button onClick={this.handClick}> click me</button>
<button onClick={this.handShow}>show</button>
<ol>
{DOME}
</ol>
<input type="text" ref='myFocus'></input>
<button onClick={this.handFocus}> focus</button>
</div>
)
}
}
export default States