我是Reactjs的新手。我收到未捕获的类型错误canvas_resize()不是函数。下面是代码段,
graphene
我不确定为什么会出现未捕获的类型错误。
答案 0 :(得分:1)
必须在生命周期方法之外声明一个函数。另外,使用箭头功能可访问函数内部的此。使用箭头功能时将具有作用域
canvas_resize = () => {
const canvas_holder = this.canvas_holder_ref.current;
const new_width = canvas_holder.clientWidth;
const new_height = canvas_holder.clientHeight;
const canvas = canvas_holder.children[0];
canvas.width = new_width;
canvas.height = new_height;
canvas.style.width = new_width + 'px';
canvas.style.height = new_height + 'px';
};
componentDidMount() {
window.addEventListener('resize', () => {
this.canvas_resize();
this.start_drawing();
});
}
OR
componentDidMount() {
const that = this;
window.addEventListener('resize', function(){
that.canvas_resize();
that.start_drawing();
});
}
但是我建议您使用箭头函数,而不要将此函数引用为函数内部的局部变量
答案 1 :(得分:0)
答案 2 :(得分:-1)
canvas_resize
方法应在componentDidMount
生命周期方法之外声明。
componentDidMount() {
window.addEventListener('resize', () => {
this.canvas_resize();
this.start_drawing();
});
}
canvas_resize = () => {
const canvas_holder = this.canvas_holder_ref.current;
const new_width = canvas_holder.clientWidth;
const new_height = canvas_holder.clientHeight;
const canvas = canvas_holder.children[0];
canvas.width = new_width;
canvas.height = new_height;
canvas.style.width = new_width + 'px';
canvas.style.height = new_height + 'px';
};