1、不使用bind
使用bind的寫法
this.handleclick.bind(this,要傳的參數(shù))
handleclick(傳過來的參數(shù),event) {
}
Eslint已經(jīng)不建議使用,可以使用ES6箭頭函數(shù)替代
handleclick= (val) => {
}
或者
handleclick(傳過來的參數(shù)) {
const _key = 傳過來的參數(shù)
const _this = this
return (event) => {
const obj = {}
obj[_key] = event.target.value
_this.setState(obj)
}
}
onChange={this.handleclick('要傳的參數(shù)')}
注意:
需要傳參數(shù),如果不使用
bind
例如:
// 傳輸點(diǎn)擊的是哪個(gè)用戶
handleUserClick = (userId) => {
console.log("ddd")
this.props.onSetCurrentUser(userId)
}
render(){
return (
<div>
<ul className="user-list">
{this.props.users.map(user=>{
return (
<li className={(this.props.currentUserId===user.id?'current':'')}
key={user.id}
onClick={this.handleUserClick(user.id)}
>
<span>{user.name}</span>
</li>
)
})}
</ul>
<input onChange={this.handleChange} value={this.state.newUser}/>
<button onClick={this.handleClick}>新增</button>
</div>
)
}
onClick={this.handleUserClick(user.id)
就會(huì)默認(rèn)執(zhí)行篱竭,因?yàn)槭茄h(huán)就會(huì)執(zhí)行n遍,而使用bind
的方法是沒問題的步绸,所以應(yīng)該改為同樣的箭頭函數(shù)綁定:
onClick={() => this.handleUserClick(user.id)}
此時(shí)加上
()=>
是返回的this.handleUserClick(user.id)
函數(shù)掺逼,而不會(huì)在加載的時(shí)候執(zhí)行一遍
2、報(bào)錯(cuò):SyntaxError: 'import' and 'export' may appear only with 'sourceType: module'
SyntaxError: 'import' and 'export' may appear only with 'sourceType: module'
在Eslint json里配置
"parserOptions": {
"ecmaFeatures": {
"experimentalObjectRestSpread": true,
"jsx": true,
"modules": true
},
"sourceType": "module",
"ecmaVersion": 7
},
3瓤介、Error: Couldn't find preset "env" relative to directory
npm i babel-preset-env
其他報(bào)錯(cuò)吕喘,例如:stage-2
npm i -D babel-preset-stage-2
4、render
如果有普通標(biāo)簽刑桑,就像vue的template需要在外邊嵌套一層div
render(){
return(
<div>
<h2>用戶列表</h2>
<UserList onAddUser={this.handleAddUser}
users={this.state.users}
onSetCurrentUser={this.handleSetCurrentUser}
currentUserId={this.state.currentUserId}
/>
</div>
)
}
5氯质、新項(xiàng)目 npm i
出錯(cuò)
不切換源,先試試升級(jí)到最新版本
npm install -g npm
如果已經(jīng)切換了源祠斧,執(zhí)行還原回來
npm config set registry https://registry.npmjs.org
6闻察、阻止冒泡事件
定義一個(gè)函數(shù)
stopPropagation = (e) => {
e.stopPropagation()
e.nativeEvent.stopImmediatePropagation()
}
使用
<html>
...
<div onClick={(event) => this.stopPropagation(event)}>
</div>
...
</html>
注意:
是否加
this
取決于使用的是有狀態(tài)組件
還是無狀態(tài)組件
7、添加多個(gè)點(diǎn)擊事件
var Test = React.createClass({
onClick(event){
func1();
func2();
},
render(){
return (
<a href="#" onClick={this.onClick}>Test Link</a>
);
}
});
或者
<a href="#" onClick={function(event){ func1(); func2()}}>Test Link</a>
ES6
<a href="#" onClick={(event) => { func1(); func2();}}>Test Link</a>