[英]React - Can't access props
我创建了一个 React 组件,它有一个canvas
和一个button
。 当组件挂载时,一个事件监听器被添加到button
中以在 canvas 上绘制一些东西。 此外,一旦执行此事件侦听器,它就会被删除。 这个组件有一个 prop 属性text
。
<Canvas text="Hello"></Canvas>
单击按钮时,我收到以下错误。 我无法访问text
道具。
TypeError
Cannot read properties of undefined (reading 'text')
零件 -
import React from "react";
class Canvas extends React.Component {
componentDidMount() {
const canvas = this.refs.canvas;
const button = this.refs.button;
const ctx = canvas.getContext("2d");
function action() {
console.log("HI")
ctx.font = "40px Consolas";
ctx.fillStyle = "#F5F5F5";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#000000";
ctx.fillText(this.props.text, 10, 40);
button.removeEventListener("click", action);
}
button.addEventListener("click", action);
}
render() {
return (
<div>
<canvas ref="canvas" width={300} height={300} />
<button ref="button" style={{
display: "block",
margin: "auto",
marginTop: "10px"
}}>Show</button>
</div>
);
}
}
export default Canvas;
根据https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#other_notes :
当使用 addEventListener() 将处理程序 function 附加到元素时,处理程序中 this 的值将是对该元素的引用。 它将与传递给处理程序的事件参数的 currentTarget 属性的值相同。
您应该在传递它时明确指定this
。
尝试这个:
import React from "react";
class Canvas extends React.Component {
componentDidMount() {
const canvas = this.refs.canvas;
const button = this.refs.button;
const ctx = canvas.getContext("2d");
function action() {
console.log("HI")
ctx.font = "40px Consolas";
ctx.fillStyle = "#F5F5F5";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = "#000000";
ctx.fillText(this.props.text, 10, 40);
button.removeEventListener("click", action);
}
const onButtonClicked = action.bind(this)
button.addEventListener("click", onButtonClicked);
}
render() {
return (
<div>
<canvas ref="canvas" width={300} height={300} />
<button ref="button" style={{
display: "block",
margin: "auto",
marginTop: "10px"
}}>Show</button>
</div>
);
}
}
export default Canvas;
出现问题是因为您无权访问 function 中的上下文。 为避免这种情况,您可以使用.bind(this)
。 你能解释一下,为什么你需要在第一次使用后删除事件监听器?
这不是很常见的事情。 我的建议是使用onClick={action}
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.