简体   繁体   中英

The dependency injection (di) paradigm with 3rd party libraries in Aurelia

I am trying to create Aurelia custom element using React, by following this example on Aurelia Q & A and following exception occurs:

Potentially unhandled rejection [1] TypeError: Cannot read property 'render' of undefined

What I am doing wrong? Here my test code:

test.html

<import from="./myelement"></import>
<my-element foo.bind="Value"></my-element>

myelement.html

<template>
  <input type="text" placeholder="user">
</template>

myelement.js

import {Behavior} from 'aurelia-framework';
import {React} from 'aurelia-framework';

export class MyElement {
  static metadata(){
    return Behavior
      .customElement('my-element')
      .withProperty('foo')
      .noView();
  }

  static inject() {
    return [Element];
  }

  constructor(element) {
    this.element = element;
    console.log('this:', this);
    console.log('element:', element);
  }

  bind() {
    // React.render(<MyReactElement foo={this.foo} />, this.element);
    React.render(React.createElement(MyReactElement, { foo: this.foo }), this.element);
  }

  fooChanged() {
    this.bind();
  }
}

The trick with importing third party libraries is you must choose how you wish to get access to the library. In your case if you are trying to create a single custom element using react that combines a view and a view model you can do so simply like this -

jspm install react

and then inside your view model -

import react from 'react'

Then you can use it anywhere in your view model, such as -

attached(element){
  // React pseudo-code
  react.render(element);
}

If you choose to load the library through dependency injection so that it is available as a module anywhere you have more options, but I think this should give you a start.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM