修正指针的3种方法
1.在构造器constructor中修正指针
优势:只执行一次
eg:
constructor(props) {
super(props);
this.Enter = this.Enter.bind(this);
}
import React,{Component} from 'react'; //导入必要的库和组件
class App extends Component {
constructor() {
super(); //ES6继承以后,必须在第一句调用父类构造器super()
this.sayHi = this.sayHi.bind(this);
}
sayHi() {
alert("hi");
console.log(this);
}
render() {
var arr = ["qq","q7","wey5"];
return(
<div>
<h1>hello world</h1>
<input type="checkbox" id="sex" value="man"/>
<label htmlFor="sex">男</label>
<button onClick={this.sayHi}>测试</button>
<ul>
{
arr.map(function(item,index){
return <li key={item}>{item}</li>
})
}
</ul>
</div>
)
}
}
export default App;
2.使用bind绑定
<div onKeyUp={this.Enter.bind(this)}></div>
<button onClick={this.sayHi.bind(this)}>测试</button>
3.利用箭头函数绑定
<div onKeyUp={(event)=>this.Enter(event)}></div>
传参的两种方式
1.onClick={()=>this.方法(参数)}
import React,{Component} from 'react'; //导入必要的库和组件
class App extends Component {
constructor() {
super(); //ES6继承以后,必须在第一句调用父类构造器super()
this.sayHi = this.sayHi.bind(this);
}
sayHi(username) {
alert("hi" + username);
console.log(this);
}
render() {
var arr = ["qq","q7","wey5"];
return(
<div>
<h1>hello world</h1>
<input type="checkbox" id="sex" value="man"/>
<label htmlFor="sex">男</label>
<button onClick={()=>this.sayHi("男神")}>测试</button>
<ul>
{
arr.map(function(item,index){
return <li key={item}>{item}</li>
})
}
</ul>
</div>
)
}
}
export default App;
2.onClick={this.方法.bind(this, 参数)}
import React,{Component} from 'react'; //导入必要的库和组件
class App extends Component {
constructor() {
super(); //ES6继承以后,必须在第一句调用父类构造器super()
this.sayHi = this.sayHi.bind(this);
}
sayHi(username) {
alert("hi" + username);
console.log(this);
}
render() {
var arr = ["qq","q7","wey5"];
return(
<div>
<h1>hello world</h1>
<input type="checkbox" id="sex" value="man"/>
<label htmlFor="sex">男</label>
<button onClick={this.sayHi.bind(this,"男神崔")}>测试</button>
<ul>
{
arr.map(function(item,index){
return <li key={item}>{item}</li>
})
}
</ul>
</div>
)
}
}
export default App;