【发布时间】:2017-04-25 04:11:33
【问题描述】:
我并不想使用 refs 做任何骇人听闻的事情。我只需要元素的引用,因为元素是画布,要在画布上绘图,您需要它的引用。
class Parent extends Component {
clickDraw = () => {
// when button clicked, get the canvas context and draw on it.
// how?
}
render() {
return (
<div>
<button onClick={this.clickDraw}> Draw </button>
<Child />
</div>
);
}
}
class Child extends Component {
componentDidMount() {
const ctx = this.canvas.getContext('2d');
// draw something on the canvas once it's mounted
ctx.fillStyle = "#FF0000";
ctx.fillRect(0,0,150,75);
}
render() {
return (
<canvas width={300}
height={500}
ref={canvasRef => this.canvas = canvasRef}>
</canvas>
);
}
}
=====
我尝试过(技术上可行但感觉很奇怪)的方法是在父组件中定义 <canvas>,因此在其 ref 函数中,this 指的是父组件。然后我将<canvas> 和this.canvas 作为两个单独的道具传递给孩子。我在孩子的渲染函数中返回<canvas>(命名为this.props.canvasJSX),并使用this.canvas(命名为this.props.canvasRef)获取它的上下文来绘制它。见下文:
class Parent extends Component {
clickDraw = () => {
// now I have access to the canvas context and can draw
const ctx = this.canvas.getContext('2d');
ctx.fillStyle = "#00FF00";
ctx.fillRect(0,0,275,250);
}
render() {
const canvas = (
<canvas width={300}
height={500}
ref={canvasRef => this.canvas = canvasRef}>
</canvas>
);
return (
<div>
<button onClick={this.clickDraw}> Draw </button>
<Child canvasJSX={canvas}
canvasRef={this.canvas} />
</div>
);
}
}
class Child extends Component {
componentDidMount() {
const ctx = this.props.canvasRef.getContext('2d');
// draw something on the canvas once it's mounted
ctx.fillStyle = "#FF0000";
ctx.fillRect(0,0,150,75);
}
render() {
return this.props.canvas;
}
}
有没有更标准的方法来实现这一点?
【问题讨论】:
-
请在父组件中使用getter和setter
标签: javascript reactjs canvas