如何在 reactjs 中动态创建 canvas 并动态添加 refs?
How to create a canvas dynamically in reactjs and add refs dynamically?
谁能告诉我如何在动态反应中创建引用?
比如我有
<canvas style={{display:'none'}} ref={(el) => this.image = el} > </canvas>
我想更动态地创作。
像这样:
<canvas style={{display:'none'}} ref={(el) => this.image1 = el} > </canvas>
<canvas style={{display:'none'}} ref={(el) => this.image2 = el} > </canvas>
<canvas style={{display:'none'}} ref={(el) => this.image3 = el} > </canvas>
那么,我可以这样做吗,或者有其他方法吗?
基本上我从服务器获取 pdf url,我正在将其转换为 canvas,然后使用它转换为图像。
我已经为一张图像完成了该操作,但要动态地执行此操作,我也必须动态创建这些引用,以便能够引用它们。
那么,我该怎么做呢?
编辑:实际上我必须过于动态地创建 img 标签并为它们创建引用,因为我想从 canvas 创建数据 url 并将其显示在图像标签中。
如果你有一个 canvas 的数组,你可以使用 map。
this.props.canvases.map((value,index)=>
<canvas ref={'canvas'+index}></canvas>
)
您可以像这样访问它:
this.refs[canvas0];
使用回调模式动态定义 refs 很容易,只需在构造函数中将 class 变量指定为一个空对象,然后在像
一样映射时设置 refs
constructor(props) {
super(props);
this.canvasRefs = {}
}
this.props.canvases.map((value,index)=> {
let id = index;
return <canvas ref={(ref) => this.canvasRefs[`canvas${id}`] = ref}></canvas>
})
您可以通过 this.canvasRefs.canvas1
、this.canvasRefs.canvas2
等方式访问它们
谁能告诉我如何在动态反应中创建引用?
比如我有
<canvas style={{display:'none'}} ref={(el) => this.image = el} > </canvas>
我想更动态地创作。
像这样:
<canvas style={{display:'none'}} ref={(el) => this.image1 = el} > </canvas>
<canvas style={{display:'none'}} ref={(el) => this.image2 = el} > </canvas>
<canvas style={{display:'none'}} ref={(el) => this.image3 = el} > </canvas>
那么,我可以这样做吗,或者有其他方法吗?
基本上我从服务器获取 pdf url,我正在将其转换为 canvas,然后使用它转换为图像。
我已经为一张图像完成了该操作,但要动态地执行此操作,我也必须动态创建这些引用,以便能够引用它们。
那么,我该怎么做呢?
编辑:实际上我必须过于动态地创建 img 标签并为它们创建引用,因为我想从 canvas 创建数据 url 并将其显示在图像标签中。
如果你有一个 canvas 的数组,你可以使用 map。
this.props.canvases.map((value,index)=>
<canvas ref={'canvas'+index}></canvas>
)
您可以像这样访问它:
this.refs[canvas0];
使用回调模式动态定义 refs 很容易,只需在构造函数中将 class 变量指定为一个空对象,然后在像
一样映射时设置 refsconstructor(props) {
super(props);
this.canvasRefs = {}
}
this.props.canvases.map((value,index)=> {
let id = index;
return <canvas ref={(ref) => this.canvasRefs[`canvas${id}`] = ref}></canvas>
})
您可以通过 this.canvasRefs.canvas1
、this.canvasRefs.canvas2
等方式访问它们