react-native 自动计算行高textInput组件

react-native 根据textInput输入文本内容自动计算输入框高度

import React from 'react';
import {
  TextInput,
} from 'react-native';

import BaseComponent from '../../components/common/baseComponent';

class AutoExpandingTextInput extends BaseComponent {
  constructor(props) {
    super(props);
    this.displayName = 'AutoExpandingTextInput';

    this.state = {
      text: '',
      height: 0,
    };
    this.onChange = this.onChange.bind(this);
  }

  onChange(event) {
    // console.log('======onChange========', event.nativeEvent);
    this.setState({
      text: event.nativeEvent.text,
      height: event.nativeEvent.contentSize.height,
    });
  }

  render() {
    const { style, textHeightMin, textHeightMax } = this.props;
    let textHeight = Math.max(textHeightMin, this.state.height);
    if (textHeight >= textHeightMax) {
      textHeight = textHeightMax;
    }
    return (
      <TextInput
        {...this.props}
        multiline={true}
        onChange={this.onChange}
        underlineColorAndroid="transparent"
        style={[style, { height: textHeight }]}
        value={this.state.text}
      />
    );
  }
}

AutoExpandingTextInput.propTypes = {
  textHeightMin: React.PropTypes.number.isRequired,
  textHeightMax: React.PropTypes.number.isRequired,
};

export default AutoExpandingTextInput;
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容