1、首先搭建一個(gè)單頁(yè)面應(yīng)用
npx create-react-app my-app
cd my-app
npm start
2、react組件
react項(xiàng)目一般都是搭配jsx語(yǔ)言使用,jsx只是js的一個(gè)語(yǔ)法擴(kuò)展,可以讓你在render里寫(xiě)dom結(jié)構(gòu)的時(shí)候能夠被識(shí)別,而且可以很好地使用表達(dá)式有提示。
我們知道,react是一個(gè)專注于組件化的框架,他在乎的是能不能再分的細(xì)致點(diǎn),當(dāng)然,這樣也能讓項(xiàng)目有更低的耦合性,以及更高的復(fù)用性,下面看看組件的兩種寫(xiě)法:
//函數(shù)式寫(xiě)法
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
//es6寫(xiě)法
class Welcome extends React.Component {
constructor(props){
super(props)
//使用了super才可以使用this 在constructor里
}
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
值得注意的是,使用es6寫(xiě)的的時(shí)候,如果想要在構(gòu)造器中使用this,必須在之前使用
super(props),至于為什么非得這么寫(xiě),可以參考這篇文章https://blog.csdn.net/huangpb123/article/details/85009024
3、再看看他的生命周期
- componentDidMount 組件渲染完成
- componentWillUnmount 組件卸載前可以調(diào)用例如:清除定時(shí)器、監(jiān)聽(tīng)
- componentWillReceiveProps(nextProps) 父組件傳給子組件props改變時(shí)使用,可以對(duì)比子組件的props,主要用于更新子組件
- shouldComponentUpdate(nextProps,nextState) 組件更新前使用 return false可組織組件重新渲染
- getSnapshotBeforeUpdate(nextProps,nextState)代替componentWillUpdate
- componentDidUpdate(preProps,preState) 每次更新都會(huì)走這里,可以拿到更新前的狀態(tài)值
4、事件
當(dāng)你在使用類的方式寫(xiě)組件的時(shí)候,這時(shí)候要注意綁定事件的方法,必須在constructor里為事件綁定this,因?yàn)橹苯诱{(diào)用事件的話,這時(shí)候打印this,可以看到是undefined,我們可以在constructor里拿到傳遞給我們的值,所以在這里綁定上this
<input type="text" value={this.props.temp} onChange={this.changeTemp} />
constructor(props) {
super(props)
this.changeTemp = this.changeTemp.bind(this)
}
changeTemp(e) {
console.log(this)
this.props.onTempChange(e.target.value)
}
解決方案,把方法寫(xiě)成函數(shù)表達(dá)式的形式
changeTemp=(e)=> {
console.log(this)
this.props.onTempChange(e.target.value)
}
5、根據(jù)條件渲染dom,以及綁定樣式
<div className='list'>
{this.state.itemList.length > 0 &&
<p>
<span>Name</span>
<span>Price</span>
</p>
}
<div className='itemList' style={{color:this.state.itemColor}}>
{this.state.itemList}
</div>
</div>
6、為表單綁定事件
一:每個(gè)input綁定一個(gè)事件,這種弊端是每個(gè)方法都得重新在構(gòu)造器綁定
<input type="text" name = 'searchTxt' onChange={this.inputChange} placeholder='search'/>
<input type="checkbox" checked={this.props.isChecked} name='isChecked' onChange={this.changeBox}/>
二:多個(gè)input用同一個(gè)方法,根據(jù)他們的name來(lái)區(qū)分到底是哪個(gè)input,這種方法弊端是如果多個(gè)input公用一個(gè)方法,那么這一個(gè)方法過(guò)于臃腫,層次不夠清晰
inputChange(e){
const value = e.target.name == 'searchTxt' ? e.target.value : e.target.checked
this.props.inputChange(e.target.name,value)
}