I’m participating in nuggets Creators Camp # 4, click here to learn more and learn together!

preface

Recently when I was playing wechat mini program, there was a requirement that the picture information should be displayed in the pop-up box. I thought of Wx. ShowModal in a moment, but I frowned after watching it for a while, and the official API did not support adding pictures in the pop-up window. At the same time, I thought it was better to customize one and familiarize myself with custom components.

Why use custom components

Some people may think that this requirement can be implemented directly in the Page page, why write a custom component?

  1. Improved code reusability: If components are not used, the code needs to be rewritten every time the same business scenario is encountered, and the removed components can be reused in their applicable scenarios, greatly improving development efficiency.
  2. Make code maintenance easier: When a component on the page has a Bug, you don’t need to look for the layout in a lot of code, you just need to look for it in the component, so this is a good example of how componentization can make code maintenance easier.

Create custom components

First we create the components directory under the root of the project to create custom components, of course you can change the English name, I have tried for you; Then we create the custom Component name in the Components directory. To make it more intuitive, we call it Multi-Modal. Then we right-click in the components directory, select New Component and name it Index. Is it a pleasant surprise to find that the directory structure is exactly the same as the page? Yes, even the writing is the same.

Implementing component layout

Since our component names are multi-modal, I would be embarrassed to say THAT I am modal if it has nothing to do with it, so we try to keep the layout style here and here consistent with the official style, so that the overall sense is more comfortable; Because the whole thing is relatively simple, we will only add the main code for introduction (see the article header activity, mainly this thing it doesn’t let me post large code).

First of all, we found the window effect of background is a layer mask, we’ll look at its main styles, the overall simple is better understood, but there is a z – the index attribute need to note that it is used to specify the stacking order of an element, if involves with other components before and after the problem, can use this property to adjust the order.

.overlay { position: fixed; top: 0; left: 0; z-index: 1; width: 100%; height: 100%; Background: RGBA (0, 0, 0, 0.7); }Copy the code

If you want to add the image information, you definitely need the image component, but it’s worth noting that the image component has to be sized by default, and the image will occupy the entire component, but the image we want to show may not be that big, which will stretch out and end up with a bad display. Here’s a little trick. We can set mode=”heightFix” to the image component. The value of this property is to adjust the zoom mode, keep the height unchanged, the width automatically changes, keep the original image aspect ratio unchanged, so that we can keep the image as good as possible.

<image class="dialog-image" src="{{image}}" mode="heightFix" wx:if="{{image}}"></image>
.dialog-image {
  width: 100%;
  height: 250rpx;
  padding: 20rpx;
  box-sizing: border-box;
}
Copy the code

If our frame only supports images obviously is not enough, so we add a description text to make it more comprehensive, and then the whole height of the frame is self-adaptive; Wait, highly adaptive? So if I have a lot of text, isn’t it… . “, sure enough, all gave me the top to the navigation bar; So we decided to add the scroll view tag, and then give it a maximum height, and then look at the effect, perfect! Here’s another tip. If you don’t want to see ugly scrollbars, use enhanced and show-scrollbar to hide them. Note that show-scrollbar values are wrapped with “{{}}”; The layout and style of other titles and confirm unclick buttons are relatively simple and will not be described here.

<scroll-view class="dialog-desc" scroll-y="true" enhanced="true" show-scrollbar="{{false}}" wx:if="{{desc}}">
      <view class="dialog-desc">{{desc}}</view>
</scroll-view>
.dialog-desc {
  width: 100%;
  max-height: 300rpx;
  font-size: 28rpx;
  font-weight: 400;
  padding: 0rpx 30rpx 30rpx;
  color: #4C4C4C;
  box-sizing: border-box;
}
Copy the code

Implementing component logic

We have completed the layout of the custom component, but the layout is not complete. Let’s look at the most important logical part of the index.js file. The following is the content of the js file created by default.

Properties: {// component property list}, data: {// component initial data}, methods: {// component method list}Copy the code

After knowing the general content, we will analyze which attributes and methods are needed. First, since it is a popover, an attribute must be required to control its display of hidden state. In addition, the title picture and content description text also need to be added dynamically, otherwise it is meaningless. So we need to define it in the external property Properties, and then do the data binding in WXML; Note here that we added wx:if to display hidden, image, and text descriptions. If this attribute is not passed in, we do not display it, which greatly increases the flexibility of use. Of course, if you don’t need the cancel button at the bottom, you can define a property value in the same way.

Properties: {show: false, // Whether to display by default hidden title: ", // popbox title: "by default hidden image:", // popbox image by default hidden desc: ", // Popup description text is hidden by default showNegative: False, // Popbox left button is hidden by default}, <view class="overlay flex-colunm-center" wx:if="{{isShow}}"> <view class="dialog-title">{{title}}</view> <image class="dialog-image" src="{{image}}" mode="heightFix" wx:if="{{image}}"></image> <scroll-view class="dialog-desc" scroll-y="true" enhanced="true" show-scrollbar="{{false}}" wx:if="{{desc}}"> <view class="dialog-desc">{{desc}}</view> </scroll-view> </view>Copy the code

Because the popbox should go away when YOU hit OK or cancel, we handle this logic directly in the custom component, but this.setData({}) can only change the value in the initial data, not the value in the external properties. Observers There is a listener that listens for changes in properties and data, so define an isShow property in the initial data, and change the value of isShow by listening for the external property show. IsShow for external attributes and show for internal attributes solves this problem; Notice which field you want to listen for and the first parameter is that field.

 observers: {
    'show': function (show) {
      this.setData({
        isShow: show
      })
    },
  },
Copy the code

It is far from enough to just pass in data. In general, we also need to get the data or state in the popbox. For example, we need to know whether the user clicks OK or cancels. Start by adding the click events bindTap =”onNegativeClick” and bindTap =”onPositiveClick” to the WXML of the custom component, and then add the click event methods to the list of component methods we mentioned in the beginning. The triggerEvent method is called triggerEvent. The first parameter is the name of the event that was triggered and used to fetch data, followed by the data that was called back after the event was triggered.

onPositiveClick(e) {
      this.triggerEvent('onPositiveClick', 'click Positive')
      this.setData({
        isShow: false
      })
    }
  }
Copy the code

Use custom components

Just now we have created a custom component, and then we will look for a page interface to see the effect. We will find the JSON file of the page and configure the name and path of the component. Multi-modal can be defined by ourselves, but the path must be accurate.

"usingComponents": {
   "multi-modal":"/components/multi-modal/index"
 }
Copy the code

Then we use the components we just defined in WXML. Make sure that the tag names are the same as those defined in your JSON file, and that the property names are the same as those of the external properties in your custom component. Note bindonNegativeClick and bindonPositiveClick. These are the callback bindings that trigger the event, and they are both in the format of “bind trigger event name” or “bind: trigger event name.” Now you know what you can do with the trigger event name defined in the custom component, and then you can define a method name to receive the trigger event data.

<multi-modal show="{{showMultiModal}}" showNegative="{{showNegative}}" 
    title="{{title}}" image="{{image}}" desc="{{desc}}" 
    bindonNegativeClick="onNegativeClick" bindonPositiveClick="onPositiveClick">
</multi-modal>
onNegativeClick(e) {
   console.log('onNegativeClick',e)
},
onPositiveClick(e) {
   console.log('onPositiveClick',e)
}
Copy the code

Now for the magic, we add a click event to the page, and we pass the showMultiModal property value to true, and let’s see what happens, and we also get the data that was sent back when WE hit OK.

conclusion

So far we finished custom components has been introduced, it simply introduces how to create a custom component that actually custom components still has a lot of properties and methods we have no reference to, but the implementation logic is the same, you can go to the official documents to practice more, so you can quickly mastered.