NumberField.js 2.7 KB
import React,{PropTypes} from 'react';
import ReactDOM from 'react-dom';  
import cx from 'classnames';
import s from './CustomForm.scss';


class NumberField extends React.Component {
    constructor(props) {
        super(props);   
        this.changeNubmer=this.changeNubmer.bind(this); 
    }
    static propTypes = {    
        displayName:PropTypes.string,
        units:PropTypes.string,
        field:PropTypes.object, 
        inlineFlag:PropTypes.bool,
        placeholder:PropTypes.string,
        readOnly:PropTypes.bool,
        customWidth:PropTypes.number,
        defaultValue:PropTypes.number,
        value:PropTypes.number,
        onChange:PropTypes.func 
    } 
    static defaultProps={
        inlineFlag:false,
        readOnly:false,
        customWidth:9,
        labelStyle:{}
    }
    validationState(field){
        if(field.error&&field.touched){
            return 'error';
        }else if(field.touched)
            return ''; 
    } 
    changeNubmer(e){
        const {field,onChange}=this.props;
        if(onChange){
            onChange(parseFloat(e.target.value));
        }else{
            field.onChange(parseFloat(e.target.value));
        } 
    }
    render(){  
        const {customWidth,displayName,inlineFlag,field,placeholder,units,readOnly,defaultValue,labelStyle}=this.props,self=this;  
        let validateState=this.validationState(field);
        const labelWidth=`col-sm-${12-customWidth}`;
        const valueWidth=`col-sm-${customWidth}`;
        let hansUnits={}
        if(units){
            hansUnits={display:'inline-block'};
        }
        return( 
            <div className={cx(s.field_wrap,'form-group',{
                'has-success':validateState=='success',
                'has-warning':validateState=='warning',
                'has-error':validateState=='error',
                'row':inlineFlag,
                'form-horizontal':inlineFlag
            })}> 
                <label className={cx('control-label',{
                    [labelWidth]:inlineFlag
                })} style={labelStyle}>{displayName}</label>
                <div className={cx(s.input_wrap,{
                    [valueWidth]:inlineFlag
                },'input-append')} >
                    <input style={hansUnits} type="number" className={cx('form-control',units?s.width_80:'')}  placeholder={placeholder} 
                    onChange={this.changeNubmer} value={field.value} readOnly={readOnly} defaultValue={defaultValue}/>  
                    <span className="add-on">{units}</span>
                    <span className={cx(s.input_help,'help-block')}><small>{field.touched?field.error:''}</small></span>
                </div>
            </div> 
        )
    }
}



export default NumberField;