【问题标题】:How do I make a TextInput show the start of the entered text instead of the end in Android?如何让 TextInput 在 Android 中显示输入文本的开头而不是结尾?
【发布时间】:2018-07-25 23:47:06
【问题描述】:

我的 react-native 应用程序中有一个 TextInput。当我设置 value 属性并且该值比 TextInput 的长度长时,它会显示从结尾而不是开头的文本。在iOS中它工​​作正常,这似乎是一个Android问题。有没有办法对齐文本以从 TextInput 的开头显示或首选哪个?

这是我看到的:

这就是我想要的:

这是我的代码

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

【问题讨论】:

  • 安卓版android:ellipsize="end"

标签: android react-native textinput


【解决方案1】:

我遇到了同样的问题,我的解决方案是默认将 selection 属性添加到开头。这有效,因此当输入聚焦时,它会开始。然后我添加了 autoFocus 属性并将其设置为 true 以使其在加载组件时开始。

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

可能有更好的方法来做到这一点,但这是我想出的,希望它可以帮助其他人。

【讨论】:

  • 但是这样用户就不能再移动光标了
  • @wong2 我想您的组件必须在更改或可能导致该问题的类似情况下重新呈现。
  • 刚才给出了和你类似的答案。但是,您不应该添加 'end' 属性,这样它会从那里开始,但不会限制用户进行更改或光标移动
  • @YossiSaadi 很好,自从我使用它已经有一段时间了,但我想我稍微记得在排除“结束”时遇到了麻烦,这可能已经随着去年的任何更新而改变,或者可能已经改变仅适用于我的特定用例。
  • @AidanDoherty 确实有点麻烦,您现在允许用户进行选择,但积极的是他可以滚动。仍然没有完美的解决方案:)
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    试试这个对我有用

    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}
    />
    

    【讨论】:

    • 它工作正常但小问题,第一次光标不移动我需要为光标位置做第二次移动。
    【解决方案4】:
    this.inputRef &&
            this.inputRef.setNativeProps({ selection: { start: 0, end: 0 } })
    

    将代码放在 onEndEditing 和任何你想更新文本的地方。

    或者同时更新文本和选择:

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

    【讨论】:

      【解决方案5】:

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

      【讨论】:

      • 我不认为这是他正在寻找的东西,这个解决方案会改变文本的截断而不是 TextInput 的起始位置。加载输入时应始终显示“开始”,然后您可以向左滑动以查看其余值。
      • ellipsizeMode prop 仅支持 Text 组件
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-29
      • 2019-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多