React 封装Input

前端之家收集整理的这篇文章主要介绍了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>
    )
  }
}
原文链接:https://www.f2er.com/react/303221.html

猜你在找的React相关文章