zoukankan      html  css  js  c++  java
  • AutoWidthInput

    import React from 'react';
    import PropTypes from 'prop-types';
    
    class AutoWidthInput extends React.Component {
    
      static propTypes = {
        value: PropTypes.string,
        placeholder: PropTypes.string,
        minWidth: PropTypes.number,
        onChange: PropTypes.func
      }
    
      static defaultProps = {
        minWidth: 28,
        onChange: () => { }
      }
    
      constructor(props) {
        super(props);
        this.state = {
          inputWidth: props.minWidth
        };
      }
    
      componentDidMount() {
        this.updateInputWidth();
      }
    
    
      componentDidUpdate() {
        this.updateInputWidth();
      }
    
      updateInputWidth = () => {
        let width = Math.max(this.sizer.scrollWidth, this.placeholderSizer.scrollWidth) + 2;
        width = Math.max(width, this.props.minWidth);
        const { inputWidth } = this.state;
        if (inputWidth !== width) {
          this.setState({ inputWidth: width });
        }
      }
      handleChange = (e) => {
        this.setState({ value: e.target.value });
        this.props.onChange(e);
      }
      render() {
        const { inputWidth } = this.state;
        const { value, placeholder } = this.props;
        return (
          <div style={{ display: 'inline-block' }}>
            <input
              style={{  inputWidth }}
              type="text"
              value={value}
              onChange={this.handleChange}
              placeholder={placeholder}
            />
            <div ref={(div) => { this.sizer = div; }} style={{ position: 'absolute', top: 0, left: 0, visibility: 'hidden', height: 0, overflow: 'scroll', whiteSpace: 'pre' }}>
              {value}
            </div>
            <div ref={(div) => { this.placeholderSizer = div; }} style={{ position: 'absolute', top: 0, left: 0, visibility: 'hidden', height: 0, overflow: 'scroll', whiteSpace: 'pre' }}>
              {placeholder}
            </div>
          </div>
        );
      }
    }
    
    export default AutoWidthInput;
    

      

  • 相关阅读:
    行为的封装
    分页功能-----》链表实现
    python入门教程链接
    作用域 属性链接 存储类型
    Codeforces Round #598 (Div. 3)
    CCPC2018-湖南全国邀请赛
    【洛谷P2494】 [SDOI2011]保密(分数规划+最小割)
    【洛谷P3329】 [ZJOI2011]最小割(最小割树)
    【BZOJ3716】[PA2014]Muzeum(贪心+网络流)
    【洛谷P4542】 [ZJOI2011]营救皮卡丘(费用流)
  • 原文地址:https://www.cnblogs.com/laneyfu/p/9299306.html
Copyright © 2011-2022 走看看