Skip to main content

Custom Component

Custom Component#

Developers can abstract feature modules in a page into custom components to reuse them in different pages, or split a page into multiple low-coupling modules for easy code maintenance. Custom components are used in almost the same way as base components.

Creating Custom Component#

Similar to a page, a custom component consists of json, bxml, bxss, and js files. To write a custom component, you first need to make a custom component declaration in the json file.

{  "component": true}

In the meanwhile, write a component template in the bxml file and a component style in the bxss file in a same way that you write a page. For details and considerations.

Code example:

<!-- This is the internal BXML structure of the custom component --><view class="inner">  {{innerText}}</view><slot></slot>
/*  This style only applies to this custom component  */.inner {  color: red;}

Note: ID selectors, attribute selectors, and tag name selectors should not be used in the component's bxss.

In the custom component's js file, you need to register the component using Component() and provide the component's property definitions, internal data, and custom methods.

The property values and internal data of the component are used to render the component's bxml. The property values are passed in from outside the component. For details, see Component Constructor.

Code example:

Component({  properties: {    // The innerText property is defined here, and the property value can be specified when the component is used.    innerText: {      type: String,      value: 'default value',    }  },  data: {    // Here are some component internal data    someData: {}  },  methods: {    // Here is a custom method    customMethod: function(){}  }})

Using Custom Component#

Before using a registered custom component, make a reference declaration in the json file of the page. You need to provide the tag name of each custom component and the file path of the corresponding custom component:

{  "usingComponents": {    "component-tag-name": "path/to/the/custom/component"  }}

As such, you can use custom components like you would with base components in the bxml of the page. The node name is the tag name of the custom component, and the node property is the property value passed to the component.

Code example:

<view>  <!-- The following is a reference to a custom component -->  <component-tag-name inner-text="Some text"></component-tag-name></view>

The custom component's bxml node structure, after being combined with the data, will be inserted into the reference location.