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 (
      
    )

    return (
      
    )
  }
}

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(
      
请输入:大牛小伙子

{this.state.source}
) } }

你可能感兴趣的:(React 封装Input)