vant Field 组件分析

1,344 阅读1分钟

简介

表单中的输入框组件。

分析

1. 布局分析

结构图如下:

整体HTML结构,融合了对Cell组件的使用,对应上图

<Cell>
    <div class="vant-field-body">
    	{this.getInput()} // 输入框
        {this.showClear && <Icon class="clear">}
        {this.genRightIcon()} // 输入框右侧icon
        {slots('button') && <div> <Button /></div>} // 右侧补充按钮,例如 发送验证码等等
    </div>
    {this.genWordLimit()} // 字数提示
    {this.genMessage()} // 错误信息
</Cell>

2. 实现详解

2.1 输入框

{
    genInput() {
    	// 1. 自定义input
    	if (inputSlot) {
        	return (<div>{inputSlot}</div>
            )
        }
        
        const inputProps = {
            on: this.listeners,
            directives: [
              {
                name: 'model',
                value: this.value,
              },
            ],
        }
        
        // 2. textarea
        if (type === 'textarea') {
        	return <textarea />
        }
        
        // 3. 设置input的inputmode属性,并返回input
        return <input type={inputType} inputmode={inputMode} {...inputProps} />;
    }
}


字数提示

genWordLimit() {
    if (this.showWordLimit && this.maxlength) {
      const count = (this.value || '').length;

      return (
        <div class={bem('word-limit')}>
          <span class={bem('word-num')}>{count}</span>/{this.maxlength}
        </div>
      );
    }
},

{ this.genWordLimit() }