簡體   English   中英

在react組件中使用自定義對象

[英]Use custom object inside react component

我想我真的不明白這個概念。 我想在react組件內創建一個自定義對象。 自定義對象本身會創建新元素。

例如:我有一個自定義對象

function LabelEditor(canvas, width, height) {

    this.canvas = canvas;
    this.canvas.width = width;
    this.canvas.height = height;
    this.canvas.id = 'mainEditor';
    this.canvas.getContext('2d');

    console.log('hi ' + this.canvas.width  + ' / ' + this.canvas.height);

    this.getCanvas = function() {
        return this.canvas;
    };
}

現在,我想在react組件中訪問此對象創建的屬性,函數和元素,如下所示:

var Editor = React.createClass({
    render: function() {
        return (
            <div>{this.props.editor.getCanvas()}</div>
        );
    }
});

React.render(
    <Editor editor={new LabelEditor(React.DOM.canvas, 500, 500)} />,
    document.getElementsByTagName('editor')[0]
);

但是到目前為止,道具,狀態和某些東西的每種組合都失敗了。

其背后的想法是,我想用fabric.js構建一個編輯器,但想在React.js應用程序中使用它。 fabric.js功能將包裝在帶有接口的自定義對象中,以控制動作。 我只想將React用作視覺部分, LabelEditor將用作控制器, fabric.js作為某種模型,提供可繪制的畫布。

下面是我如何構造代碼( 請參見此JSBin上的有效演示)。 基本上,編輯器組件呈現<canvas> ,您將在componentDidMount()實例化LabelEditor。 您使用React.findDOMNode()是因為render() <canvas>代表虛擬DOM,因此您需要找到相應的DOM。 現在, LabelEditor可以繪制圖形。

function LabelEditor(canvas, width, height) {
  this.canvas = canvas;
  this.canvas.width = width;
  this.canvas.height = height;
  this.canvas.id = 'mainEditor';

  // Draw something
  var ctx = this.canvas.getContext('2d');
  ctx.fillStyle = "#A0EBDD"
  ctx.fillRect(30, 30, 150, 150);
}

var Editor = React.createClass({
  componentDidMount: function() {
    var canvas = React.findDOMNode(this.refs.canvas);
    this._editor = new LabelEditor(canvas, this.props.width, this.props.height);
  },

  render: function() {
    return (
      <canvas ref="canvas"></canvas>
    );
  }
});

React.render(
  <Editor width={500} height={500} />,
  document.getElementById('editor')
);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM