【发布时间】:2018-03-19 02:29:00
【问题描述】:
我正在尝试创建一个 UI 以与 fabricjs 画布进行交互。左侧是一个组件,显示可以添加到画布的项目库。中间是fabricjs画布,右边是一个组件,列出了画布上所有添加的项目(类似于photoshops图层面板)。
我想知道如何在左侧的组件 (ItemsList.js) 中有一个 onClick 事件,访问在其父组件中声明的 fabricjs 画布实例。
这是主要组件...
MainComponent.js
import React, { Component } from 'react';
import { createContainer } from 'meteor/react-meteor-data';
import ItemsList from './ItemsList.js';
import LayersPanel from './LayersPanel.js';
import {fabric} from 'fabric';
class Designer extends React.Component {
constructor(props) {
super(props);
this.state = {
canvasWidth: ''
};
}
updateCanvasDimensions() {
this.setState({
canvasWidth: this.refs.canvas_wrapper.offsetWidth
});
canvas.setHeight(this.state.canvasWidth);
canvas.setWidth(this.state.canvasWidth);
}
componentDidMount() {
canvas = new fabric.Canvas('c', {
width: this.refs.canvas_wrapper.offsetWidth,
height: this.refs.canvas_wrapper.offsetWidth
});
this.updateCanvasDimensions(canvas);
window.addEventListener("resize", this.updateCanvasDimensions.bind(this));
canvas.renderAll();
}
componentWillUnmount() {
window.removeEventListener("resize", this.updateCanvasDimensions.bind(this));
}
render() {
return (
<div>
<div>
<ItemsList />
</div>
<div className="canvas-wrapper" ref="canvas_wrapper">
<canvas ref="c" id = "c"></canvas>
</div>
<div>
<LayersPanel />
</div>
</div>
);
}
}
export default createContainer(({ params }) => {
return {
};
}, Designer);
在 ItemsList.js 中的某处,对于列表中的每个项目,都有一个用于将项目的图像添加到画布的按钮。
...
<Button onClick={() => {
//Need to get the canvas instance here so
//that I can add this particular item's image to the canvas like this...
canvas.add(rowData.image);
}}>Add Item</Button>
...
在为 ItemsList 组件中的特定项目单击此按钮后,我希望将单击的项目的图像添加到树上组件中声明的画布中。比如……
<MainComponent> <-- This is where I declare the fabric canvas.
<ItemsList>
<Item/> <-- This is where the button is clicked.
</ItemsList>
</MainComponent>
如何从<Item/> 中访问画布实例?
如果它与答案相关,同时我还需要右侧的组件(<LayersPanel/>)来显示添加到画布的内容。
谢谢
【问题讨论】: