# Component(Object object)

Creates a custom component that takes an argument of typeObject.

# parameter

# Object object

Definition paragraph type Is it compulsory? describe Minimum version
properties Object Map no The external properties of a component are a mapping table from the property name to the property settings.
data Object no Component internal data, along withpropertiesfor template rendering of components
observers Object no A component data field monitor that listens for changes in properties and data. See Data Monitor 2.6.1
methods Object no Component methods, including event-response functions and any custom methods. For the use of event-response functions, see Intercomponent communication and events
behaviors String Array no Intercomponent code reuse mechanisms similar to mixins and traits, see behaviors
created Function no Component Life-periodic function - When a component instance is created, note thatsetData cannot be invoked
attached Function no Component life periodic function - executed when a component instance enters the page node tree
ready Function no Component Life-periodic function - executed after component layout is completed
moved Function no Component life periodic function - executed when the component instance is moved to another location in the node tree
detached Function no Component life periodic function - executed when a component instance is removed from the page node tree
relations Object no Inter-component relationship definition, see Inter-component relationship
externalClasses String Array no External style classes accepted by the component, see External style classes
options Object Map no Some options (specific option settings will be involved when referring to the features in the documentation, but will not be enumerated here)
lifetimes Object no Component lifecycle declaration object, see Component lifecycle 2.2.3
pageLifetimes Object no Lifecycle declaration object for the page where the component resides, see Component Lifecycle 2.2.3

The generated component instance can be accessed throughthisin [] serverof the component's methods, life-periodic functions, and properties.The components contain some common properties and methods.

Attribute Name type describe
is String The file path of the component
id String NodeID
dataset String node dataset
data Object Component data, including internal data and attribute values
properties Object Component data, including internal data and attribute values (consistent withdata)
router Object Router object relative to the current custom component
pageRouter Object Router object relative to the page where the current custom component resides
renderer string The rendering back end for rendering the current component
Method Name parameter describe Minimum version
setData ObjectnewData Set data and perform visual layer rendering
hasBehavior Objectbehavior Check if the component hasbehavior(check recursively for all behavior that is introduced directly or indirectly)
triggerEvent Stringname, Objectdetail, Objectoptions Trigger events, see Inter-component Communication and Events
createSelectorQuery Create a SelectorQuery object, the selector selects within the component instance
createIntersectionObserver Creates a IntersectionObserver object, the selector selects within the component instance
createMediaQueryObserver Create a MediaQueryObserver object 2.11.1
selectComponent Stringselector Use the selector to select the component instance node and return the first component instance object that matches (affected bywx: / / component-export)
selectAllComponents Stringselector Use the selector to select a component instance node and return an array of all the matching component instances that will be [[]]wx: / / component-export
selectOwnerComponent Choose the component instance where the current component node resides (i.e. the component reference), and return its component instance object (which will be [[]]wx: / / component-export 2.8.2
getRelationNodes StringrelationKey Gets all associated nodes for this relationship. See Component Relations
groupSetData Functioncallback Immediately executecallback,MultiplesetDatado not trigger interface painting (this is only needed in certain special scenarios, such as for synchronizing interface painting when different components setData at the same time). 2.4.0
getTabBar Returns the component instance of the custom-tab-bar for the current page, see Custom tabBar 2.6.2
getPageId Returns the page identifier (a character string) that can be used to determine if several custom component instances are on the same page 2.7.1
animate Stringselector, Arraykeyframes, Numberduration, Functioncallback Perform keyframe animation, see Animation 2.9.0
clearAnimation Stringselector, Objectoptions, Functioncallback Clear keyframe animation, see Animation 2.9.0
applyAnimatedStyle Stringselector, Functionupdater, Objectconfig, Functioncallback Bind worklet-driven styles to the corresponding node, see worklet animation 2.29.0
clearAnimatedStyle Stringselector, ArraystyleIds, Functioncallback Clear bindings for worklet driven styles on nodes 2.30.1
setUpdatePerformanceListener Objectoptions, Functionlistener Set the update performance statistics receiver function, see Get update performance statistics 2.12.0

# ApplyAnimatedStyle parameter definition

Definition paragraph type Is it compulsory? describe Minimum version
selector String yes Node Selector 2.29.0
updater Function yes Worklet Style Update Function 2.29.0
userConfig Object no Configuration items 2.30.1
callback Function no Finish a callback for style binding 2.30.1

# Definition of configuration items

attribute type Default values describe
immediate boolean true Do you want to perform an updater function immediately?
flush string async Refresh timing, enumeration value async / sync

Selectoris synonymous with SelectorQuery.select .

By default, theupdaterfunction will be executed once, and the result will be applied to the node as an initial value, setting theimmediate: falseskips the first execution.

The set of styles supported by theStyleObjectreturned by the updaterfunction refers to the skyline wxss style .StyleObjectThe key is the hump of the css attribute.

When the dependentsharedValuevalue is updated, theupdaterfunction is re-executed and the newstyleis applied to the selected node.By default, the new style takes effect on the next render slice (better performance), setting theflush: syncThis makes it effective on the current rendering time frame.

CallbackCallback returnsstyleIdthat can be used to clear style bindings.

const offset = shared(0)
const styleIds = []
this.applyAnimatedStyle('.box', () => {
  'worklet'
  return {
    transform: `translateX(${offset.value}px) rotate(30deg)`
  }
}, {
  immediate: true,
  flush: 'async'
}, (res) => {
  console.log('animatedStyle 已绑定到节点 ', res.styleId)
  styleIds.push(res.styleId)
})

this.clearAnimatedStyle('.box', styleIds, () => {
  console.log('animatedStyle 已清除绑定')
})

# ClearAnimatedStyle Parameter Definition

Definition paragraph type Is it compulsory? describe Minimum version
selector String yes Node Selector 2.30.1
styleIds Array yes The styleId collection that needs to be cleared 2.30.1
callback Function no Clear callbacks for style binding 2.30.1

The styleIdsarray is empty, then all boundanimatedStyleon the selected node is cleared,Note that the style does not reset, but simply removes the dependencies.styleIdcan be obtained fromapplyAnimatedStylecallback parameter.

When the node is removed, the relevantanimatedStyleis automatically released, andclearAnimatedStylecan be used when you need to unbind earlier.

# sample code

Preview with Developer Tool

Component({

  behaviors: [],

  // 属性定义(详情参见下文)
  properties: {
    myProperty: { // 属性名
      type: String,
      value: ''
    },
    myProperty2: String // 简化的定义方式
  },

  data: {}, // 私有数据,可用于模板渲染

  lifetimes: {
    // 生命周期函数,可以为函数,或一个在methods段中定义的方法名
    attached: function () { },
    moved: function () { },
    detached: function () { },
  },

  // 生命周期函数,可以为函数,或一个在methods段中定义的方法名
  attached: function () { }, // 此处attached的声明会被lifetimes字段中的声明覆盖
  ready: function() { },

  pageLifetimes: {
    // 组件所在页面的生命周期函数
    show: function () { },
    hide: function () { },
    resize: function () { },
  },

  methods: {
    onMyButtonTap: function(){
      this.setData({
        // 更新属性和数据的方法与更新页面数据的方法类似
      })
    },
    // 内部方法建议以下划线开头
    _myPrivateMethod: function(){
      // 这里将 data.A[0].B 设为 'myPrivateData'
      this.setData({
        'A[0].B': 'myPrivateData'
      })
    },
    _propertyChange: function(newVal, oldVal) {

    }
  }

})

Note: In thepropertiesdefinition paragraph, property names are humped (propertyName);Inwxml, a hyphen is used to specify attribute values (component-tag-name property-name = "attr value"), which is used in data binding with a hump (attr="")。

# PropertiesDefinition

Definition paragraph type Is it compulsory? describe Minimum version
type yes Type of attribute
optionalTypes Array no Type of attribute (multiple can be specified) 2.6.5
value no The initial value of the property
observer Function no Callback function when property values change

Changes in property values can be monitored using observers.Currently, it is not recommended to use this field in the new version of the repository, but rather to use the Component builder'sobserversfield, which is more powerful and performs better.

__Note: In the__definition paragraph, thetypeThefield is a required__entry, although {% version ('2.17.2') %} the base library above has increased compatibility with unfilled fields (compatibility with filled fields when unfilled).null), but lower versions of the base library can't handle unfilled cases, and at worst may render the page incorrectly. Please note compatibility.

# sample code

Component({
  properties: {
    min: {
      type: Number,
      value: 0
    },
    max: {
      type: Number,
      value: 0,
      observer: function(newVal, oldVal) {
        // 属性值变化时执行
      }
    },
    lastLeaf: {
      // 这个属性可以是 Number 、 String 、 Boolean 三种类型中的一种
      type: Number,
      optionalTypes: [String, Object],
      value: 0
    }
  }
})

Attribute can be of typeString``Number``Boolean``Object``ArrayFirst, you can also usenullto denote the unrestricted type.

In most cases, it's best to specify an exact type for an attribute. This way, when the attribute value is specified as a literal in WXML, the value gets an exact type, such as:

<custom-comp min="1" max="5" />

At this point, since the corresponding attribute of the custom component is specified asNumberType,minandmaxwill be assigned the values1and]]5, rather than"1"and"5", namely:

this.data.min === 1 // true
this.data.max === 5 // true

# Bug & Tip

  • Internal data and attribute values can be obtained usingthis.data;However, modifying it directly will not apply the changes to the interface and should be modified usingsetData.
  • Life-periodic functions cannot be accessed in a component method throughthis.
  • Attribute names should avoid starting with data, that is, do not namedataXyzIn this form, because in WXML,data-xyz = ""is treated as a node dataset, not as a component property.
  • When a component is defined and used, the component's property names and data fields cannot conflict with each other (although they are in different definitions).
  • Starting with the base library {% version ('2.0.9')}, the object-type properties and data fields can contain subfields of the function type, that is, functions can be passed through the object-types properties fields.Libraries below this version do not support this feature.
  • Bug: The custom component located in slot did not trigger the page lifecycle declared inpageLifetimes. This problem was fixed in {% version ('2.5.2')}.
  • Bug: For attributes of type Object or Array,If a subfield of the attribute value is changed through the component's own this.setData, the attribute observer is still triggered, and the observer receives thenewValis the value of the child field that is changed,oldValis empty,changedPathcontains information about the field name of the child fields;It is currently recommended to use theobserversdefinition paragraph instead.