背景

开发微信小程序 textarea组件的时候,希望能有一个清除按钮,清空textarea输入的值,但是发现添加完按钮以后,得连按两次才能清除掉。
<view class="flex-row-center" style="margin-top: 30rpx;">
<textarea class="input" value="{{prompt}}" name="prompt" bindblur='bindTextAreaBlur' placeholder="{{placeholder}}" maxlength = "-1"/>
</view>
<view class="flex-row" style="margin-top: 12rpx;">
<image src="../../images/image-clear.png" bindtap='clearPrompt' style="margin-left: 180rpx;width: 45rpx;height: 45rpx;"></image>
</view>
clearPrompt: function () {
this.data.prompt = '';
this.setData({
prompt: '',
});
},
原因
由于失去焦点,键盘回落没有及时触发清空,从而发现需要点击两下删除才清空,解决办法就是用定时器延迟触发清空


上面的代码修改为
clearPrompt: function () {
var _this = this;
setTimeout(function () {
_this.data.prompt = '';
_this.setData({
prompt: '',
});
}, 100)
},