JavaScript实现一个输入框组件

Bena ·
更新时间:2024-09-20
· 550 次阅读

本文实例为大家分享了手动实现一个输入框组件的具体代码,供大家参考,具体内容如下

背景

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); } } } }



输入 JavaScript 输入框

需要 登录 后方可回复, 如果你还没有账号请 注册新账号