基礎(chǔ)看完了载矿,現(xiàn)在來記錄一下state和props
state
class listData extends React.Component{
//es6 的 語法垄潮,詳情請出門右轉(zhuǎn)看ES6
constructor(...props){
super(...props)
//也就這個(gè)state這個(gè)沒有用react自己的getInitialState
this.state = {
testState:true
}
}
//其他的react生命周期照樣可以使用,不過恢准,注意沒有逗號~
componentDidMount(){
// ajax code balabala
}
changeState(){
this.setState({
testState: !this.state.testState
},()=>{
//這個(gè)是setState的第二個(gè)參數(shù)魂挂,也就是一個(gè)function,就是一個(gè)回調(diào)函數(shù)馁筐,在state修改完之后涂召,你想做的事情就可以放在這里
console.log(this.state.testState);
//如果不是在setState的回調(diào)里打印state的話,是沒有改變之前的state敏沉,因?yàn)閟etState是異步操作
})
}
render(){
return(
<div onClick = {this.changeState.bind(this)}>測試那么一下</div>
)
}
}
上面是示例代碼果正,現(xiàn)在來BB一下相關(guān)東西
state呢,個(gè)人理解盟迟,是一個(gè)全局的超級大對象秋泳,也就是react提倡的虛擬dom的根本(我這么理解的,鍵盤俠勿擾)
可以把任何東西掛載在state中攒菠,當(dāng)然后通過setState改變你要改變的state相應(yīng)屬性迫皱,react會(huì)自己幫你判斷你在引用該state的地方是否需要更新。
那么問題來了,如果你頻繁操作state卓起,小的倒還好和敬,ajax返回后的state一般數(shù)據(jù)量比較大,如何處理戏阅?總不能每次都要比對全部的state昼弟,對吧?
如果你遇到了奕筐,屆時(shí)請記得拆分舱痘,也就是把這種數(shù)據(jù)量大的state單獨(dú)拎出去創(chuàng)建一個(gè)新的組件類。然后使用react生命周期中的 shouldComponentUpdate 离赫。
生命周期相關(guān)芭逝,會(huì)在后面整理,這里提一下笆怠。使用詳情铝耻,先自行查一下吧。
設(shè)置state還可以使用
setState((prevState,props)=>{
fuck:!prevState.fuck
}) // props不用的時(shí)候可以不傳
props
props是父子組件之間傳值
let Parent = React.createClass({
getInitialState({
return{
tabIndex:1
}
}),
render(){
return(
<div>
<Child parent = {this}/>//把需要傳給子組件的東西放在這里蹬刷,可以直接把父組件的this傳給子組件
</div>
)
}
});
let Child = React.createClass({
render(){
return(
<div>{this.props.parent.state.tabIndex}</div> //this.props.parent取到的就是父組件傳過來的this,父組件的this都拿到了,那么父組件里的其他東西也就可以拿到了频丘。
//也可以傳其他的办成,類似于回調(diào)等
)
}
})
再補(bǔ)一種寫法
{
this.state.dialogShow ?
<Dialog title="title" content="content"
sureCall={this.sure.bind(this)} cancelCall = {()=>this.setState({dialogShow:false})}>
<input className="addTagNameInput" value={this.state.editInput} defaultValue="" placeholder="請輸入名稱" onChange={(e)=>{this.setState({editInput:e.target.value})}}/>
</Dialog> : null
}
因?yàn)檫@里只是負(fù)責(zé)展示,并沒有什么邏輯搂漠,所以沒有使用class Dialog extends React...來編寫
這種是普通的無狀態(tài)組件
props是父級調(diào)用的時(shí)候傳入的所有
function Dialog(props){
//從傳入的props里解構(gòu)出來需要的東西
const{title,sureCall,cancelCall,children,content=""} = props;
return (
<div className={content ? content + " cover" : "cover"}>
<div className="delDialog">
<div className="dialogTitle">
<p>{title}</p>
<span onClick = {cancelCall}></span>
</div>
<div className="dialogCon" >
{children}
</div>
<div className="dialogBtn">
<span className="sure" onClick = {sureCall}>
確定
</span>
<span className="cancel" onClick = {cancelCall}>
取消
</span>
</div>
</div>
</div>
)
}
這里的children迂卢,是<Dialog></Dialog>標(biāo)簽中間的東西,可以是元素標(biāo)簽也可以是文字
如果不需要額外的children,可以直接<Dialog />傳入就可以了桐汤。