如果将 multiline 设置为 true,React Native 将接受 TextInput 中的无限行,有 maxLength 但它只是限制最大字符数,那么如何设置 TextInput 的最大行数呢?
你可以使用maxHeight和minHeight接受你想要的。对于标准文本 fontSize,给予maxHeight={60}将使 TextInput 在 3 行后可滚动。这对 IOS 有好处 - 对于 Android,您可以使用numberOfLinesprop。
我创建了一个简单的版本来扩展 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)
我认为 iOS 上不行。如前所述,Android 有 prop numberOfLines。我能想到的最接近的方法是尝试估计输入的宽度并根据该尺寸限制字符,但我认为这可能是一条黑暗的道路。
如果您选择这样做,有人正在尝试获取此处的行数。onLayout获取 TextInput 宽度并onChangeText限制它的函数组合可能会起作用。
| 归档时间: |
|
| 查看次数: |
21233 次 |
| 最近记录: |