+
95
-

回答

在微信小程序中实现单选其它可输入选择框效果,可以通过结合 picker 组件和 input 组件来实现。具体步骤如下:

使用 picker 组件实现下拉选择

picker 组件可以用来实现下拉选择功能。当用户选择“其它”选项时,显示 input 组件供用户输入自定义文字。

使用 input 组件实现自定义输入

input 组件可以用来接收用户的自定义输入。当用户选择“其它”选项时,显示 input 组件,否则隐藏。

以下是一个示例代码,展示了如何实现这一功能:

<!-- index.wxml -->
<view class="container">
  <picker mode="selector" range="{{options}}" value="{{selectedIndex}}" bindchange="onPickerChange">
    <view class="picker">
      {{options[selectedIndex]}}
    </view>
  </picker>
  <input wx:if="{{showInput}}" type="text" placeholder="请输入自定义内容" bindinput="onInputChange" />
</view>
/* index.wxss */
.container {
  padding: 20px;
}

.picker {
  border: 1px solid #ccc;
  padding: 10px;
  border-radius: 5px;
}

input {
  margin-top: 20px;
  border: 1px solid #ccc;
  padding: 10px;
  border-radius: 5px;
}
// index.js
Page({
  data: {
    options: ['选项1', '选项2', '选项3', '其它'],
    selectedIndex: 0,
    showInput: false,
    customText: ''
  },

  onPickerChange(e) {
    const selectedIndex = e.detail.value;
    const showInput = this.data.options[selectedIndex] === '其它';
    this.setData({
      selectedIndex,
      showInput,
      customText: ''
    });
  },

  onInputChange(e) {
    this.setData({
      customText: e.detail.value
    });
  }
});
解释

picker 组件

mode="selector" 表示这是一个单选的下拉选择器。range="{{options}}" 表示下拉选项的数据源。value="{{selectedIndex}}" 表示当前选中的索引。bindchange="onPickerChange" 表示当选择改变时触发的事件。

input 组件

wx:if="{{showInput}}" 表示当 showInput 为 true 时显示该输入框。bindinput="onInputChange" 表示当输入内容改变时触发的事件。

事件处理函数

onPickerChange:当选择改变时,更新选中的索引,并根据选择的选项决定是否显示输入框。onInputChange:当输入内容改变时,更新自定义输入的文本。

通过这种方式,你可以在微信小程序中实现一个单选其它可输入选择框效果。

网友回复

我知道答案,我要回答