【问题标题】:React Native - TextInput focus while onClick Text Label won't workReact Native - onClick 文本标签时的文本输入焦点不起作用
【发布时间】:2021-08-27 09:14:13
【问题描述】:

我只是想让文本输入焦点更容易获得更用户友好的应用程序。当用户错过单击文本输入并单击文本时,我会尝试这样做,它应该专注于文本输入。

所以我将 ref 添加到 text as

  <Text ref={"textref"}

在文本输入上

 <TextInput onPress={_onPress => { this.refs.textref.focus() }} 

它适用于 1 个单词的标签文本,但不适用于长文本。我能做什么?

它还说不推荐使用 refs 是否有更好的方法来做到这一点?我发现这种方式最短且有效,但遗憾的是它已被弃用。

编辑:我修好了。

<Text onPress={() => {this.inputText.focus()}} 
<TextInput ref={input => { this.inputText= input}}   

为我工作。

【问题讨论】:

    标签: javascript react-native focus textinput ref


    【解决方案1】:

    首先,您尝试关注文本,但您只能关注 TextInput

    那么,我建议你在构造函数中初始化你的 ref

    constructor(props) {
        super(props)
        
        ...
    
        this.textInputref = React.createRef()
    }
    

    <Text onPress={() => this.textInputref.current.focus()}>hello world</Text>
    
    <TextInput ref={this.textInputref} /> 
    

    【讨论】:

    • 我想我需要休息一下,哈哈。现在我按照你所说的进行了更改,但它给出了错误,因为 this2.textref.focus 不是函数
    • 试试 this.textInputref.current.focus()
    • 我刚刚在另一个问题中找到了解决方法。我做了 {this.textInput.focus()}} 和 { this.textInput= input}} 它起作用了。
    【解决方案2】:

    你可以这样使用:

    <Text onPress={_onPress => { this.refs.textref.focus() }}> Testing </Text>
    <TextInput ref={"textref"}/> 
    

    【讨论】:

    • 我这样使用它,但它说 refs 已被弃用。我发现这对我有用的解决方案。 {this.input.focus()}}>点击我 { this.input = input}}/ >
    猜你喜欢
    • 2021-10-15
    • 2017-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-25
    • 2022-08-24
    相关资源
    最近更新 更多