React 封装Input

需要的第三方库:react | prop-types | classnames | 等等
两个页面 Input.js | input.less
Input.js

import React,{Component} from 'react';
import {PropTypes} from 'prop-types';
import classNames from 'classnames';
import './input.less'

export default class Input extends Component {
  constructor(props){
    super(props);
    this.state = {
      value:props.value
    }
  }

  componentwillReceiveProps(props){
    if(props.value !== this.props.value){
      this.setState({value:props.value})
    }
  }
  handleChange(e){
    const { onChange,length } = this.props;
    let val = e.target.value
    if(val.length > length){
      e.target.value = val;
    }
    this.setState({value:val})
    onChange && onChange(e,val)
  }

  render(){
    const {prefixCls,style,className,children,type,length,...other} = this.props;
    const cls = classNames(className,`${prefixCls}`,{'textarea':type ==='textarea'})
    if(type==='textarea') return (
      <textarea
        className={classNames(cls,`${prefixCls}-inner`)}
        {...other}
        style={style}
        type={type}
        onChange={this.handleChange.bind(this)}
      >
      </textarea>
    )

    return (
      <input 
        {...other} 
        className={classNames(cls,`${prefixCls}-inner`)} 
        type={type} 
        style={style}
        onChange={this.handleChange.bind(this)}
      />
    )
  }
}

DaNiu.propTypes = {
  prefixCls:PropTypes.string,type:PropTypes.string,}

DaNiu.defaultProps = {
  prefixCls:'d-input',type:"text",}

input.less

.d-input{
  position: relative;
}
.d-input-inner{
  // iOS 中使用appearance修改输入框样式
  appearance: none;
  background-color: #fff;
  background-image: none;
  border-radius: 5px;
  border: 1px solid #E8E8E8;
  Box-sizing: border-Box;
  color: #1f2d3d;
  font-size: inherit;
  width: 100%;
  height: 30px;
  line-height: 14px;
  outline: 0;
  padding: 3px 10px;
  display: inline-block;
  transition: #0fa120 0.5 ease-in;
  &:hover{
    border:1px solid #aeaeae;
  }
  &:focus{
    border-color: #0fa120;
    Box-shadow: 0 0 0 2px rgba(84,220,103,0.14);
  }
  &:focus&::placeholder{
    color:#d5d5d5;
  }
}


组件引用
Index.js

import React,{Component} from 'react';
import './index.less'

import Input from './Input'


export default class Index extends Component{
  constructor(props){
    super(props);
    this.state={
      visible:false,loading:true,source:''
    }

  }
  
  onChange(e,value){
    console.log('e',value)
    value && value === '大牛小伙子' ? this.setState({source:value}) : this.setState({source:''})
  }



  render(){
    return(
      <div>
         请输入:大牛小伙子<br/>
        <Input style={{width:200,marginTop:10,marginBottom:10}} onChange={this.onChange.bind(this)}/><br/>
        <div>{this.state.source}</div>
      </div>
    )
  }
}

相关文章

react 中的高阶组件主要是对于 hooks 之前的类组件来说的,如...
我们上一节了解了组件的更新机制,但是只是停留在表层上,例...
我们上一节了解了 react 的虚拟 dom 的格式,如何把虚拟 dom...
react 本身提供了克隆组件的方法,但是平时开发中可能很少使...
mobx 是一个简单可扩展的状态管理库,中文官网链接。小编在接...
我们在平常的开发中不可避免的会有很多列表渲染逻辑,在 pc ...