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

我有multiline道具设置,所以它是包装但文档似乎没有提到任何有关包装的事件,我唯一能想到的是一个真正的hacky策略,字符计数,以确定何时增加输入的高度.我怎么做到这一点?
https://facebook.github.io/react-native/docs/textinput.html
Jér*_*rin 47
感谢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}
/>
);
}
}
Run Code Online (Sandbox Code Playgroud)
0.46.1或更高:(由NicolasdeChevigné解释)
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}
/>
);
}
}
Run Code Online (Sandbox Code Playgroud)
Nic*_*e C 33
自React Native 0.46.1起:
contentSize属性已从TextInput.onChange事件中删除
如果您使用此版本,则可以处理onContentSizeChange道具
从Jérémy回答,我们有
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}
/>
);
}
}
Run Code Online (Sandbox Code Playgroud)
Yai*_*pro 18
你应该只在下面设置一个maxHeight属性style:
<TextInput multiline style={{maxHeight: 80}} />
Run Code Online (Sandbox Code Playgroud)
在这里演示:https://snack.expo.io/@yairopro/multiline-input-with-max-height
小智 7
我的答案是在 TextInput 中使用onContentSizeChangeand numberOfLinesprops ,当然打开multiline,这是我的解决方案:
let numOfLinesCompany = 0;
<TextInput
...
multiline={true}
numberOfLines={numOfLinesCompany}
onContentSizeChange={(e) => {
numOfLinesCompany = e.nativeEvent.contentSize.height / 18;
}}
/>
Run Code Online (Sandbox Code Playgroud)
18 是文本的高度,可能取决于 fontSize
| 归档时间: |
|
| 查看次数: |
26535 次 |
| 最近记录: |