如何从nativescript中的js注入自定义组件?

Aka*_*wal 6 nativescript

假设我创建了一个小组件,它接受一个输入并设置一个标签来显示它.

应用/组件/ testComponent/testComponent.xml:

<Label id="someLabel" loaded="onLoad"/>
Run Code Online (Sandbox Code Playgroud)

应用/组件/ testComponent/testComponent.js:

exports.onLoad = args => {
    const obj = args.object;

    const label = obj.getViewById('someLabel');
    label.text = obj.someString || 'no string given';
};
Run Code Online (Sandbox Code Playgroud)

现在我可以在任何页面中使用此组件

<Page xmlns="http://schemas.nativescript.org/tns.xsd"
      xmlns:testComponent="components/testComponent">
    <StackLayout>
        <testComponent:testComponent someString="hello {N}"/>
    </StackLayout>
</Page>
Run Code Online (Sandbox Code Playgroud)

这似乎是正式的方式,它的工作原理.但有没有办法只使用javascript在页面中注入此组件?

Nat*_*ael 9

是的,Declarative UI(即xml)实际上是一个构建系统,它解析xml并生成JS,所以你不必这样做.

因此,如果您想手动执行此操作,您将单独保留组件代码,并将主屏幕代码更改为:

<Page xmlns="http://schemas.nativescript.org/tns.xsd" loaded="onLoad">
    <StackLayout id='sl'>

    </StackLayout>
</Page>
Run Code Online (Sandbox Code Playgroud)

您将注意到的第一件事是我们为Page提供了一个已加载的事件,您必须在某处实际运行代码以将组件附加到可视树.我们做的第二件事是向StackLayout添加一个id; 这在技术上实际上并不需要 - 您可以导航NS树并找到正确的StackLayout; 但为简单起见,添加ID会使其更容易.


所以你页面中的JS代码是:

var builder = require('ui/builder');
var fs = require('file-system');

exports.onLoad = function(args) {
  // Get our current Page that is being loaded
  var page = args.object;

  // Find our StackLayout
  var stackLayout = page.getViewById('sl');

  // Load our JS for the component
  var path = fs.knownFolders.currentApp().path;
  var componentJS = require(path + '/components/testComponent/testComponent.js');

  // Actually have the builder build the Component using the XML & JS.
  var component = builder.load(path + '/components/testComponent/testComponent.xml', componentJS);

  // And add our component to the visual tree
  stackLayout.addChild(component);
};
Run Code Online (Sandbox Code Playgroud)

我相信,因为您正在加载的事件中添加子项,您的子组件中的页面加载事件将被运行,但不要让我持有那个.如果不是那么你可以在添加它的同时手动运行它...