Skip to main content
Version: 3.x

Best Practices

About the JSX support added

Because the JSX in writing, we can't support to all JSX wording, due to the limit WeChat small process at the same time, also has some excellent JSX usage temporarily can't get a good support, in this added level of support for the JSX:

The above rules in Taro generated by default template has ESLint detection, without doing any configuration. If your editor is not installed ESLint plug-in can refer to the following tutorial in your editor installation:

By default Taro compiler will to warn of unable to run the code, when there is no call stack information code can be generated. If you need to drop ESLint disabled at compile time checking, can in order before joining ESLint=false parameters, such as:

$ ESLINT=false taro build --type weapp --watch

The best encoding

After a long time of exploration and verification, the Taro on WeChat applet is to use a mini-app that relies on native custom components system to realize the Taro, modular design, so the mini-app the componentization is limited by a mini-app native component system, while at the same time in order to achieve the goal of writing the code in the React way, Taro itself made some compile-time and runtime processing, it also brought some noteworthy constraints, so it is necessary to elaborate Taro coding best practices.

Component style description

WeChat mini-app Custom components default is not affected by the external style, such as to quote for a custom components in the page, write directly in the page style custom component elements of the style is unable to take effect. In this, Taro, too, and that is with all of you cognition of traditional Web development are different.

To the component set defaultProps

In the WeChat mini-app custom components, only in properties specified in the properties, can be introduced into and received from the parent component

Component({
properties: {
myProperty: { // The property name
type: String, // Type (required), currently accepted types include: String, Number, Boolean, Object, Array, null (any type)
value: '', // Properties of the initial value (optional), if not specified will choose according to the type
observer: function (newVal, oldVal, changedPath) {
// Property is a function to be executed by the change (optional), also can be written as defined in the methods section of the method name string, such as: '_propertyChange'
// NewVal is a new set of data, usually oldVal is old data
}
},
myProperty2: String // The definition of simplified way
}
...
})

In Taro, for use in component code to from props attributes, can be identified at compile time and join the compiled properties, temporary support for the following writing

this.props.property

const { property } = this.props

const property = this.props.property

There are one thousand Hamlet in the heart, but one thousand people of different people code written certainly is not the same, so the compilation of Taro certainly cannot cover all the writing, And at the same time may have a certain attribute is not used directly passed to the child components, no matter what also can't handle this kind of circumstance is compile time, at this time requires everyone to component Settings when coding defaultProps to solve the.

Component set defaultProps will be handled at run time to make up for the compile time less than, all attributes will be set to properties initialization of the component, is set up correctly defaultProps can avoid the occurrence of a lot of abnormal condition.

Attribute names to components transfer function on beginning

In v1.3.0 - beta. 0, the custom event passed between components can need not on beginning, But the events of the built-in components still is on beginning, for the sake of consistency we still recommend you to on start naming your event.

Components in Taro, father to son module transfer function, the attribute name must start with on beginning

// Call the Custom components, the incoming handleEvent function, attribute called onTrigger
class Parent extends Component {

handleEvent () {

}

render () {
return (
<Custom onTrigger={this.handleEvent}></Custom>
)
}
}

This is because the end componentization WeChat small procedure is cannot directly transfer function type to child components, is with the help of a component in the Taro event mechanism to implement this feature, and the mini-app in the attribute name written for incoming events bindmyevent or bind:myevent

<!-- When fire myevent event custom components, call onMyEvent method -->
<component-tag-name bindmyevent="onMyEvent" />
<!-- Or can be written as -->
<component-tag-name bind:myevent="onMyEvent" />

So the property name component in the Taro agreed transfer function with on beginning, at the same time it also consistent with built-in component event binding method.

mini-app end don't print in the component incoming function

Since the v1.3.0 - beta. 0 no this limit

As mentioned earlier on the mini-app components to function principle, so don't print the component on the mini-app end incoming function, because can't get the result, but this.props.onXxx && this.props.onXxx() The judging function is passed to the calling method is fully supported.

Don't put in the mini-app end template used in the data set to undefined

Due to the mini-app does not support the data in any of the terms of the value is set to undefined, when setState also please avoid such use. You can use null to replace.

mini-app end don't printthis.props.children in the components

On WeChat applet is through <slot /> to realize to the incoming elements in custom components, and Taro use this.props.children implements the function at compile time, this.props.children can be directly compiled into <slot /> label, so it belongs to the existence of the syntactic sugar in a mini-app end, please don't print it in the component.

Introduced into JSX support props

Since the 1.1.9 began to support

Support to JSX props, but element to JSX attribute name must be in render beginning

Child components, for example

class Dialog extends Component {
render () {
return (
<View className='dialog'>
<View className='header'>
{this.props.renderHeader}
</View>
<View className='body'>
{this.props.children}
</View>
<View className='footer'>
{this.props.renderFooter}
</View>
</View>
)
}
}

The parent component calls subcomponents are introduced into JSX

class App extends Component {
render () {
return (
<View className='container'>
<Dialog
renderHeader={
<View className='welcome-message'>Welcome!</View>
}
renderFooter={
<Button className='close'>Close</Button>
}
>
<View className="dialog-message">
Thank you for using Taro.
</View>
</Dialog>
</View>
)
}
}

Component property transfer notice

Do not regard id, class, style as the name of the property with the internal state of custom components, because the property name in small WeChat program applications will be lost.

In the component state and props field name repetition

Don't state and props on in the field with the same name, because these fields in WeChat mini-app will hang in data.

mini-app page lifecycle componentWillMount inconsistency problem

Due to their small WeChat program page in onLoad routing parameters to get a page, the page before the onLoad components have attached. So the page componentWillMount could be in line with expectations are not too. Such as:

// Error term
render () {
// Couldn't get before willMount routing parameters
const abc = this.$router.params.abc
return <Custom adc={abc} />
}

// Correct term
componentWillMount () {
const abc = this.$router.params.abc
this.setState({
abc
})
}
render () {
// Add a compatible judgment
return this.state.abc && <Custom adc={abc} />
}

For does not need to wait until after page willMount routing parameters page would not have any effect.

Components of constructor and render call ahead of time

Many developers should have noticed carefully, after Taro compilation to mini-app, component constructor and render default will call one more time, don't act and React.

This is because the components of Taro compiled custom components is a mini-app, and the mini-app initialization time of custom components can be specified data to make components have initialized data. Developers generally in the component constructor sets some initialization state, at the same time, it may be in render handling state and props generate new data, in Taro extra call ahead of time, this time is to collect the component initialization data, to custom components generated in advance data, to ensure that the can with data when the component initialization, let the first render normal components.

So, in code, need to do some fault tolerance in dealing with data processing, so that we can avoid the constructor and render call appear error due to no data in advance.

JS code must use single quotation marks

In Taro, JS code must be written in single quotes, especially in the JSX, if a double quotation marks, may cause a compiler error.

The use of the environment variable process.env

Don't want to get through in the form of deconstruction env configuration process.env environment variables, please directly to complete writing process.env.NODE_ENV for use

// Error writing, does not support
const { NODE_ENV = 'development' } = process.env
if (NODE_ENV === 'development') {
...
}

// Correct term
if (process.env.NODE_ENV === 'development') {

}

Using this.$componentType ponent is to determine the current Taro.Component page or component

this.$componentType possible values respectively PAGE or COMPONENT, developers can according to the value of the variable respectively, take different logic.

mini-app that native components pass props to Taro components

Taro v1.3+ the props system is reformed, make can't compatible with primary component by the properties of incoming attribute.

Now can put all the props need to Taro component, by using extraProps attribute to solve.

// mini-app component conventional props
<plugin title="{{name}}" desc="{{desc}}" bindonclick="onClick"></plugin>

// Native mini-app component calls Taro components need to transform into the following form:
this.setData({
extraProps: {
name,
desc,
onClick: this.onClick
}
})
<plugin extraProps="{{extraProps}}" ></plugin>

Global Variable

Is recommended to use in the Taro Redux for the management of the global variables, but for small applications, Redux may seem heavy, at that time if you want to use global variables, recommend the following use.

A new self named JS files, such as global_data. JS, sample code is as follows

const globalData = {}

export function set (key, val) {
globalData[key] = val
}

export function get (key) {
return globalData[key]
}

Then it can be used in any position

import { set as setGlobalData, get as getGlobalData } from './path/name/global_data'

setGlobalData('test', 1)

getGlobalData('test')