React Native 限制 TextInput 中的行数

Jus*_*tin 8 react-native

如果将 multiline 设置为 true,React Native 将接受 TextInput 中的无限行,有 maxLength 但它只是限制最大字符数,那么如何设置 TextInput 的最大行数呢?

Dav*_*vid 9

你可以使用maxHeightminHeight接受你想要的。对于标准文本 fontSize,给予maxHeight={60}将使 TextInput 在 3 行后可滚动。这对 IOS 有好处 - 对于 Android,您可以使用numberOfLinesprop。


Fel*_*shi 6

我创建了一个简单的版本来扩展 TextInput 以提供 maxLines 功能。

import React, { Component } from "react";
import { TextInput } from "react-native";
import PropTypes from "prop-types";

export default class MultiLine extends Component {
  static propTypes = {
    maxLines: PropTypes.number
  };

  constructor(props) {
    super(props);
    this.state = {
      value: props.value || ""
    };
  }

  onChangeText = text => {
    const { maxLines, onChangeText } = this.props;
    const lines = text.split("\n");

    if (lines.length <= (maxLines || 1)) {
      onChangeText(text);
      this.setState({ value: text });
    }
 };

 render() {
   const { onChangeText, multiline, value, ...other } = this.props;
   return (
     <TextInput
       {...other}
       multiline={true}
       value={this.state.value}
       onChangeText={this.onChangeText}
     />
   );
 }
}
Run Code Online (Sandbox Code Playgroud)

一个例子:

<Multiline
  value={this.state.testeText}
  maxLines={10}
  onChangeText={text => {
    this.setState({ testeText: text });                
  }}
/>
Run Code Online (Sandbox Code Playgroud)


klv*_*lvs 0

我认为 iOS 上不行。如前所述,Android 有 prop numberOfLines。我能想到的最接近的方法是尝试估计输入的宽度并根据该尺寸限制字符,但我认为这可能是一条黑暗的道路。

如果您选择这样做,有人正在尝试获取此处的行数。onLayout获取 TextInput 宽度并onChangeText限制它的函数组合可能会起作用。