简体   繁体   English

如何让 TextInput 在 Android 中显示输入文本的开头而不是结尾?

[英]How do I make a TextInput show the start of the entered text instead of the end in Android?

I have a TextInput in my react-native application.我的 react-native 应用程序中有一个TextInput When I set the value prop and the value is longer than the length of the TextInput , it shows the text starting from the end and not the beginning.当我设置值 prop 并且值比TextInput的长度长时,它显示从末尾而不是开头的文本。 In iOS it works okay, it seems to be an Android issue.在 iOS 中它工作正常,这似乎是一个 Android 问题。 Is there a way to align the text to show from the start of the TextInput or whichever is the preferred?有没有办法将文本从TextInput的开头或首选显示对齐?

This is what I see:这是我看到的:

在此处输入图片说明

This is what I want:这就是我想要的:

在此处输入图片说明

Here's my code这是我的代码

<TextInput
defaultValue={address}
ref="searchInput"
autoCorrect={false}
style={searchStyles.searchInputField}
placeholderTextColor={'#ddd'}
placeholder="Location"
onChangeText={query => this.search(query)}
/>

I ran into the same issue my solution for this was adding the selection prop to the start by default.我遇到了同样的问题,我的解决方案是默认将选择道具添加到开始。 This works so when the input is focused it goes to the start.这是有效的,因此当输入聚焦时,它会进入开始。 I then added the autoFocus prop and set it to true to make it go to the start when the component is loaded.然后我添加了autoFocus道具并将其设置为 true 以使其在加载组件时进入开始状态。

<TextInput value={address} autoFocus={true} selection={{start:0, end:0}} />

There may be a better way to do this but this is what i have come up with hope it helps others.可能有更好的方法来做到这一点,但这是我提出的希望它可以帮助其他人。

添加selection={{start:0}}不带end属性

try this its working for me试试这个对我有用

constructor(props) {
 super(props);
 
 this.state = {
   selection: Platform.OS === 'android' ? { start: 0 } : null
 }
}

onFocus =()=>{
  if(Platform.OS==='android'){
    this.setState({ selection:null });
  }
}

onBlur =()=>{
  if(Platform.OS==='android'){
    this.setState({ selection:{ start: 0, end: 0 } });
  }
}

<TextInput
  onFocus={()=>this.onFocus()}
  onBlur={()=>this.onBlur()}
  selection={this.state.selection}
/>
this.inputRef &&
        this.inputRef.setNativeProps({ selection: { start: 0, end: 0 } })

Put the code in onEndEditing and wherever you want to update the text.将代码放在 onEndEditing 中以及您想要更新文本的任何位置。

Or update the text and selection at the same time:或者同时更新文本和选择:

this.inputRef &&
        this.inputRef.setNativeProps({ text: value, selection: { start: 0, end: 0 } })

ellipsizeMode="head"或者你可以试试ellipsizeMode="tail"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM