我定义了两个TextInput字段如下:

<TextInput 
   style = {styles.titleInput}
   returnKeyType = {"next"}
   autoFocus = {true}
   placeholder = "Title" />
<TextInput
   style = {styles.descriptionInput}          
   multiline = {true}
   maxLength = {200}
   placeholder = "Description" />

但在按下键盘上的“next”按钮后,我的react-native应用程序并没有跳转到第二个TextInput字段。我怎样才能做到呢?

谢谢!


当前回答

RN没有某种类型的Tabindex系统,这很令人恼火。

一个功能性组件,对于我的用例,我有一个字符串id数组用于输入,我遍历并显示每个文本输入。下面的代码将自动跳过所有这些,阻止键盘在字段之间消失/重新出现,并在结束时解散它,还在键盘上显示适当的“动作”按钮。

Typescript, Native Base。

const stringFieldIDs = [ 'q1', 'q2', 'q3' ]; export default () => { const stringFieldRefs = stringFieldIDs.map(() => useRef < any > ()); const basicStringField = (id: string, ind: number) => { const posInd = stringFieldIDs.indexOf(id); const isLast = posInd === stringFieldIDs.length - 1; return ( < Input blurOnSubmit = { isLast } ref = { stringFieldRefs[posInd] } returnKeyType = { isLast ? 'done' : 'next' } onSubmitEditing = { isLast ? undefined : () => stringFieldRefs[posInd + 1].current._root.focus() } /> ); }; return stringFieldIDs.map(basicStringField); };

其他回答

使用react-native 0.45.1我还遇到了问题,试图在按下用户名TextInput的返回键后将焦点设置在密码TextInput上。

在尝试了这里的大多数顶级解决方案之后,我在github上找到了一个解决方案,满足了我的需求: https://github.com/shoutem/ui/issues/44#issuecomment-290724642

总结一下:

import React, { Component } from 'react';
import { TextInput as RNTextInput } from 'react-native';

export default class TextInput extends Component {
    render() {
        const { props } = this;

        return (
            <RNTextInput
                {...props}
                ref={(input) => props.inputRef && props.inputRef(input)}
            />
        );
    }
}

然后我这样使用它:

import React, {Component} from 'react';
import {
    View,
} from 'react-native';
import TextInput from "../../components/TextInput";

class Login extends Component {
    constructor(props) {
        super(props);
        this.passTextInput = null
    }

    render() {
        return (
            <View style={{flex:1}}>
                <TextInput
                    style={{flex:1}}
                    placeholder="Username"
                    onSubmitEditing={(event) => {
                        this.passTextInput.focus()
                    }}
                />

                <TextInput
                    style={{flex:1}}
                    placeholder="Password"
                    inputRef={(input) => {
                        this.passTextInput = input
                    }}
                />
            </View>
        )
    }
}

在你的组件中:

constructor(props) {
        super(props);
        this.focusNextField = this
            .focusNextField
            .bind(this);
        // to store our input refs
        this.inputs = {};
    }
    focusNextField(id) {
        console.log("focus next input: " + id);
        this
            .inputs[id]
            ._root
            .focus();
    }

注意:我使用了._root,因为它是NativeBase' library ' Input中的TextInput的引用

在文本输入中,像这样

<TextInput
         onSubmitEditing={() => {
                          this.focusNextField('two');
                          }}
         returnKeyType="next"
         blurOnSubmit={false}/>


<TextInput      
         ref={input => {
              this.inputs['two'] = input;
                        }}/>

从React Native 0.36开始,不再支持在文本输入节点上调用focus()(在其他几个答案中建议)。相反,你可以使用React Native中的TextInputState模块。我创建了以下帮助模块,使这更容易:

// TextInputManager
//
// Provides helper functions for managing the focus state of text
// inputs. This is a hack! You are supposed to be able to call
// "focus()" directly on TextInput nodes, but that doesn't seem
// to be working as of ReactNative 0.36
//
import { findNodeHandle } from 'react-native'
import TextInputState from 'react-native/lib/TextInputState'


export function focusTextInput(node) {
  try {
    TextInputState.focusTextInput(findNodeHandle(node))
  } catch(e) {
    console.log("Couldn't focus text input: ", e.message)
  }
}

然后,您可以在TextInput的任何“ref”上调用focusTextInput函数。例如:

...
<TextInput onSubmit={() => focusTextInput(this.refs.inputB)} />
<TextInput ref="inputB" />
...

下面是如何为reactjs的电话代码输入实现这一点

import React, { useState, useRef } from 'react';

function Header(props) {

  const [state , setState] = useState({
        phone_number:"",
        code_one:'',
        code_two:'',
        code_three:'',
        code_four:'',
        submitted:false,

  })

   const codeOneInput = useRef(null);
   const codeTwoInput = useRef(null);
   const codeThreeInput = useRef(null);
   const codeFourInput = useRef(null);

   const handleCodeChange = (e) => {
        const {id , value} = e.target
        if(value.length < 2){
            setState(prevState => ({
                ...prevState,
                [id] : value
            }))
            if(id=='code_one' && value.length >0){
                codeTwoInput.current.focus();
            }
            if(id=='code_two'  && value.length >0){
                codeThreeInput.current.focus();
            }
            if(id=='code_three'  && value.length >0){
                codeFourInput.current.focus();
            }
        }
    }

    const sendCodeToServer = () => {

         setState(prevState => ({
                ...prevState,
                submitted : true,
          }))
  let codeEnteredByUser = state.code_one + state.code_two + state.code_three + state.code_four

        axios.post(API_BASE_URL, {code:codeEnteredByUser})
        .then(function (response) {
            console.log(response)
        })

   }

   return(
        <>

           <div className="are">
                 <div className="POP-INN-INPUT">
                                        <input type="text" id="code_one" ref={codeOneInput}    value={state.code_one}  onChange={handleCodeChange} autoFocus/>
                                        <input type="text" id="code_two"  ref={codeTwoInput}  value={state.code_two} onChange={handleCodeChange}/>
                                        <input type="text" id="code_three"  ref={codeThreeInput} value={state.code_three}  onChange={handleCodeChange}/>
                                        <input type="text" id="code_four" ref={codeFourInput}  value={state.code_four}  onChange={handleCodeChange}/>
                                    </div>

            <button disabled={state.submitted} onClick={sendCodeToServer}>
   
    </div>

       </>
    )
}
export default

你不需要裁判也可以做到。这种方法是首选的,因为引用会导致脆弱的代码。React文档建议在可能的情况下寻找其他解决方案:

If you have not programmed several apps with React, your first inclination is usually going to be to try to use refs to "make things happen" in your app. If this is the case, take a moment and think more critically about where state should be owned in the component hierarchy. Often, it becomes clear that the proper place to "own" that state is at a higher level in the hierarchy. Placing the state there often eliminates any desire to use refs to "make things happen" – instead, the data flow will usually accomplish your goal.

相反,我们将使用一个状态变量来聚焦第二个输入字段。

Add a state variable that we'll pass as a prop to the DescriptionInput: initialState() { return { focusDescriptionInput: false, }; } Define a handler method that will set this state variable to true: handleTitleInputSubmit() { this.setState(focusDescriptionInput: true); } Upon submitting / hitting enter / next on the TitleInput, we'll call handleTitleInputSubmit. This will set focusDescriptionInput to true. <TextInput style = {styles.titleInput} returnKeyType = {"next"} autoFocus = {true} placeholder = "Title" onSubmitEditing={this.handleTitleInputSubmit} /> DescriptionInput's focus prop is set to our focusDescriptionInput state variable. So, when focusDescriptionInput changes (in step 3), DescriptionInput will re-render with focus={true}. <TextInput style = {styles.descriptionInput} multiline = {true} maxLength = {200} placeholder = "Description" focus={this.state.focusDescriptionInput} />

这是避免使用refs的好方法,因为refs会导致更脆弱的代码:)

编辑:h/t @LaneRettig指出,你需要用一些添加的道具和方法来包装React Native TextInput,以获得对焦点的响应:

    // Props:
    static propTypes = { 
        focus: PropTypes.bool,
    } 

    static defaultProps = { 
        focus: false,
    } 

    // Methods:
    focus() {
        this._component.focus(); 
    } 

    componentWillReceiveProps(nextProps) {
        const {focus} = nextProps; 

        focus && this.focus(); 
    }