class app extends Component {
constructor(props) {
super(props);
this.changeable = this.changeable.bind(this);
}
changeable (){
alert('hi');
}
componentDidMount(){
let arr= document.getElementsByClassName("scene")[0].children; //arr3是集合不是数组,所以后续要将集合赋值给数组。
let arr1=[];
for(let i=0;i<arr.length;i++){
arr1[i]=arr[i];
}
arr1.map( (item,index) => {
item.οnclick=function(){
this.changeable() //此时会报错,说changeble is not a function
}
})
}
原本我以为是componnet函数中无法调用this,后来发现是因为item.onclick事件中,this指向的对象是item数组元素,也就是 document.getElementsByClassName("scene")[0].children。
这样一来就简单了,直接提前保存this的值就ok啦 :
arr1.map( (item,index) => {
var thi = this;
item.οnclick=function(){
thi.changeable()
}
})
是我脑子瓦特了