微信小程序自定义搜索框(searchbar)

本文介绍了一种在微信小程序中实现自定义搜索框的方法,包括样式调整、用户交互及代码实现细节。通过组件化的方式,使搜索框的使用更加灵活,可根据需求进行扩展。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

微信小程序自定义搜索框(searchbar)

样式截图展示:未输入关键字样式展示
输入关键字后样式展示

功能描述:微信小程序页面需要加入搜索框时,可以直接引用到页面中使用,当用户未输入任何关键字时如第一张图所示,当用户输入要搜索的关键字时如第二张图所示,出现取消文案和清空的icon标识,点击取消文案或者清空的icon标识,都可清空关键字,样式恢复到第一张图所示


实现代码:

(1) searchbar.js

Component({
  properties: {
    placeholder: {
      type: String,
      value: '',
    }
  },
  data: {
    inputValue: ''
  },
  methods: {
    // 用户输入触发
    handleInput: function(e) {
      this.setData({
        inputValue: e.detail.value
      })
    },
    // 点击清空输入框icon
    handleDeleteClick: function() {
      this.setData({
        inputValue: ''
      })
    },
    // 点击取消触发
    handleTextbtnClick() {
      // 触发父组件中的方法
      this.setData({
        inputValue: ''
      })
    },
    // 用户点击确定触发
    handleConfirm() {
      this.triggerEvent('handleSearch', this.data.inputValue)
    }
  }
})

(2) searchbar.json

{
  "component": true
}

(3) searchbar.wxml

<view class="searchbar">
  <view class="content">
    <image src="../../assets/images/search.png" class="search-icon"></image>
    <input 
      bindinput="handleInput"
      bindconfirm="handleConfirm"
      type="text"
      value="{{inputValue}}" 
      placeholder="{{placeholder}}" 
      class="input"
      confirm-type="search"
    ></input>
    <image
     wx:if="{{inputValue}}" 
     bindtap="handleDeleteClick"
     src="../../assets/images/delete-circle.png" 
     class="delete-icon"
    ></image>
  </view>
  <view wx:if="{{inputValue}}" bindtap="handleTextbtnClick" class="text-btn">取消</view>
</view>

(4) searchbar.wxss

.searchbar {
  height: 88rpx;
  padding: 20rpx 30rpx;
  display: flex;
}
.content {
  height: 88rpx;
  padding: 0 18rpx;
  background: rgba(255,255,255,1);
  border-radius: 16rpx;
  border: 2rpx solid rgba(220,222,226,1);
  flex: 1;
  display: flex;
  align-items: center;
}
.search-icon {
  width: 34rpx;
  height: 34rpx;
  margin-bottom: -4rpx;
}
.input {
  flex: 1;
  margin: 0 20rpx;
}
.delete-icon {
  width: 40rpx;
  height: 40rpx;
}
.text-btn {
  margin-left: 24rpx;
  height: 88rpx;
  line-height: 88rpx;
  font-size: 32rpx;
  font-family: PingFangSC;
  font-weight: 400;
  color: rgba(21,96,220,1);
}

使用方法:(假如在index的页面中使用searchbar组件)
(1)在index.json文件中引入搜索组件searchbar

{
  "usingComponents": {
    "searchbar": "../../components/searchbar/searchbar"
  }
}

(2) 在index.wxml文件中

<searchbar
  placeholder="请输入关键字"
  bind:handleSearch="handleSearch"
></searchbar>

总结: 以上就是自定义searchbar组件的实现及使用方法,如果样式或者用户的交互有不同,可以直接在代码中做扩展。

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

www.www

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值