美文网首页
react-native 自动计算行高textInput组件

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

作者: reloadRen | 来源:发表于2016-09-05 10:39 被阅读974次

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;

相关文章

网友评论

      本文标题:react-native 自动计算行高textInput组件

      本文链接:https://www.haomeiwen.com/subject/thdrettx.html