手动实现一个输入框组件

背景

taro h5中想要实现一个样式如下的输入框:

在这里插入图片描述
问题:
taro组件和taro-ui组件中都没有这种样式的组件,taro h5 中还不支持修改placeholder的样式,自己尝试着实现一个input组件,更能灵活的定义其中的样式。

实现

js代码

import Taro, { Component } from '@tarojs/taro';
import { View } from '@tarojs/components';
import { AtIcon } from 'taro-ui';

import './index.scss';

/**
 * @description 手动实现一个输入框组件
 * @param placeholder:String 自定义输入框中的占位符
 * @param onClickSearch:Function 获取输入内容回调
 */
class BaseInput extends Component {
  componentDidMount() {
    //输入框聚焦
    document.querySelector('.search').focus();
  }

  handleSearch = () => {
    //获取输入框的内容
    const value = document.querySelector('.search').innerText;
    this.props.onClickSearch && this.props.onClickSearch(value);
  };

  render() {
    const { placeholder = '请输入' } = this.props;
    return (
      <View className="base_input">
        <View className="my_search">
          <AtIcon
            value="search"
            color="#999"
            className="search_icon"
            onClick={this.handleSearch}
          />
          {/* contenteditable可以控制一个div是否可以编辑 */}
          <View
            className="search"
            contenteditable
            placeholder={placeholder}
          ></View>
        </View>
      </View>
    );
  }
}
export default BaseInput;

scss代码

.base_input {
  .my_search {
    box-sizing: border-box;
    width: 690px;
    height: 56px;
    line-height: 56px;
    border-radius: 28px;
    margin: 12px auto;
    background: #f8f8f8;
    display: flex;
    .search_icon {
      width: 30px;
      height: 30px;
      margin-left: 20px;
      margin-right: 18px;
    }
    .search {
      width: 560px;
      padding: 0px 18px;
      background: #f8f8f8;
      height: 56px;
      color: #999;
      font-size: 28px;
      font-weight: 400;
      &:empty::after {
        content: attr(placeholder);
      }
    }
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值