本文介绍了我将如何成长 <TextInput>文字环绕的高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个 <TextInput> ,当文本换行到下一行时,它可以增加高度,类似于 Slack 的消息输入如何随着文本增长到某一点.

I'm trying to create a <TextInput> that can grow in height when the text wraps to the next line, similar to how Slack's message input grows with the text up to a point.

我有 multiline 道具集,所以它正在包装,但文档似乎没有提到任何关于包装的事件,我唯一能想到的就是一个非常古怪的角色策略计数以确定何时增加输入的高度.我将如何做到这一点?https://facebook.github.io/react-native/docs/textinput.html

I have the multiline prop set, so it is wrapping but the docs don't seem to mention any event regarding wrapping, and the only thing I can think of is a really hacky strategy to character count to figure out when to increase height of the input. How would I accomplish this?https://facebook.github.io/react-native/docs/textinput.html

推荐答案

感谢 react-native 文档:https://facebook.github.io/react-native/docs/textinput.html

Thanks to react-native doc: https://facebook.github.io/react-native/docs/textinput.html

你可以这样做:

class AutoExpandingTextInput extends React.Component {
  state: any;

  constructor(props) {
    super(props);
    this.state = {text: '', height: 0};
  }
  render() {
    return (
      <TextInput
        {...this.props}
        multiline={true}
        onChange={(event) => {
          this.setState({
            text: event.nativeEvent.text,
            height: event.nativeEvent.contentSize.height,
          });
        }}
        style={[styles.default, {height: Math.max(35, this.state.height)}]}
        value={this.state.text}
      />
    );
  }
}

0.46.1 或更高版本:(由 Nicolas de Chevigné 解释)

0.46.1 or higher: (as explained by Nicolas de Chevigné)

class AutoExpandingTextInput extends React.Component {

  constructor(props) {
    super(props);
    this.state = {text: '', height: 0};
  }
  render() {
    return (
      <TextInput
        {...this.props}
        multiline={true}
        onChangeText={(text) => {
            this.setState({ text })
        }}
        onContentSizeChange={(event) => {
            this.setState({ height: event.nativeEvent.contentSize.height })
        }}
        style={[styles.default, {height: Math.max(35, this.state.height)}]}
        value={this.state.text}
      />
    );
  }
}

这篇关于我将如何成长 &lt;TextInput&gt;文字环绕的高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-14 17:44