自适应高度的多行文本输入框AutoTextInput是一种常用需求,在RN官方文档上就有其demo
class AutoExpandingTextInput extends {
constructor(props) {
super(props);
this.state = {
text: 'React Native enables you to build world-class application experiences on native platforms using a consistent developer experience based on JavaScript and React. The focus of React Native is on developer efficiency across all the platforms you care about — learn once, write anywhere. Facebook uses React Native in multiple production apps and will continue investing in React Native.',
height: 0,
};
}
render() {
return (
<TextInput
{...this.props}
multiline={true}
onContentSizeChange={(event) => {
this.setState({height: event.nativeEvent.contentSize.height});
}}
onChangeText={(text) => {
this.setState({text});
}}
style={[styles.default, {height: Math.max(35, this.state.height)}]}
value={this.state.text}
/>
);
}
}
export default class AutoTextInput extends Component {
constructor(props) {
super(props);
this.onContentSizeChange = this.onContentSizeChange.bind(this);
this.onChange = this.onChange.bind(this);
this.state = {
height: 0,
};
}
onContentSizeChange(event) {
let height = event.nativeEvent.contentSize.height;
this.changeHeight(height);
}
onChange(event) {
if (Platform.OS === 'android') {
let height = event.nativeEvent.contentSize.height;
this.changeHeight(height);
}
}
changeHeight(height) {
let {
minHeight = 16,
maxHeight,
} = this.props;
if (height < minHeight) {
height = minHeight;
} else if (maxHeight && height > maxHeight) {
height = maxHeight;
}
if (height !== this.state.height) {
this.setState({height: height});
}
}
render() {
return (
<TextInput
{...this.props}
multiline
onContentSizeChange={this.onContentSizeChange}
onChange={this.onChange}
style={[this.props.style, {height: this.state.height}]}
/>
)
}
}