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;
网友评论