我定义了两个TextInput字段,如下所示:
<TextInput
style = {styles.titleInput}
returnKeyType = {"next"}
autoFocus = {true}
placeholder = "Title" />
<TextInput
style = {styles.descriptionInput}
multiline = {true}
maxLength = {200}
placeholder = "Description" />
但是在按下键盘上的“下一步”按钮后,我的react-native应用程序没有跳转到第二个TextInput字段 . 我怎样才能做到这一点?
谢谢!
15 回答
当前一个
TextInput
的onSubmitEditing
被触发时,设置第二个TextInput
焦点 .试试这个
将参考添加到 second TextInput
ref={(input) => { this.secondTextInput = input; }}
将焦点函数绑定到 first TextInput 的onSubmitEditing事件 .
onSubmitEditing={() => { this.secondTextInput.focus(); }}
切记将blurOnSubmit设置为false,以防止键盘闪烁 .
blurOnSubmit={false}
你可以这样做 without using refs . 这种方法是首选,因为refs可以导致 fragile code . React docs建议尽可能找到其他解决方案:
相反,我们将使用状态变量来聚焦第二个输入字段 .
DescriptionInput
的状态变量:TitleInput
上提交/点击进入/下一步后,我们将调用handleTitleInputSubmit
. 这会将focusDescriptionInput
设置为true .DescriptionInput
的focus
prop设置为我们的focusDescriptionInput
状态变量 . 因此,当focusDescriptionInput
更改(在步骤3中)时,DescriptionInput
将使用focus={true}
重新渲染 .这是避免使用refs的好方法,因为refs会导致更脆弱的代码:)
编辑:h / t @LaneRettig指出你需要用一些添加的道具和方法包装React Native TextInput来让它响应
focus
:从React Native 0.36开始,不再支持在文本输入节点上调用
focus()
(如其他几个答案所示) . 相反,您可以使用React Native中的TextInputState
模块 . 我创建了以下帮助程序模块以使其更容易:然后,您可以在
TextInput
的"ref"上调用focusTextInput
函数 . 例如:我创建了一个小型库来执行此操作,除了替换包装视图和导入TextInput之外,不需要更改代码:
https://github.com/zackify/react-native-autofocus
这里详细解释:https://zach.codes/autofocus-inputs-in-react-native/
使用react-native 0.45.1我在按用户名TextInput上的返回键后尝试将焦点设置为密码TextInput时也遇到了问题 .
在这里尝试了大多数评价最高的解决方案后,我在github上找到了满足我需求的解决方案:https://github.com/shoutem/ui/issues/44#issuecomment-290724642
把它们加起来:
然后我像这样使用它:
如果您正好像我一样使用tcomb-form-native,那么您也可以这样做 . 这是诀窍:不是直接设置
TextInput
的道具,而是通过options
来实现 . 您可以将表单的字段称为:所以最终产品看起来像这样:
(感谢remcoanker在这里发布这个想法:https://github.com/gcanti/tcomb-form-native/issues/96)
对我来说,RN 0.50.3可以用这种方式:
你必须看到这个.PasswordInputRef . _root .focus()
在React Native的GitHub问题上尝试这个解决方案 .
https://github.com/facebook/react-native/pull/2149#issuecomment-129262565
您需要为TextInput组件使用ref prop .
然后你需要创建一个在onSubmitEditing prop上调用的函数,该函数将焦点移动到第二个TextInput引用 .
使用回调引用而不是legacy字符串引用:
如果您的
TextInput
在另一个组件中,则可以使用已接受的解决方案,您需要ref
从ref
到父容器的引用 .这是我实现它的方式 . 下面的示例使用了React 16.3中引入的React.createRef()API .
我想这会对你有所帮助 .
有一种方法可以在
TextInput
中捕获 tabs . 这是hacky,但比nothing更好 .定义一个
onChangeText
处理程序将新输入值与旧输入值进行比较,检查\t
. 如果找到一个,请按@boredgames所示前进该字段假设变量
username
包含用户名的值,并且setUsername
调度在商店中更改它的操作(组件状态,redux存储等),请执行以下操作:在您的组件中:
注意:我使用
._root
,因为它是NativeBase'Library' Input中的TextInput引用并在你的文字输入这样
我的场景是 < CustomBoladonesTextInput /> 包裹RN < TextInput /> .
我解决了这个问题如下:
我的表格如下:
在CustomBoladonesTextInput的组件定义中,我将refField传递给内部ref prop,如下所示:
瞧 . 一切都恢复正常 . 希望这可以帮助
这里是具有:focus属性的输入组件的试剂解决方案 .
只要此prop为true,就会聚焦该字段,只要这是假的,就不会有焦点 .
不幸的是这个组件需要有一个:ref定义,我找不到另一种方法来调用.focus() . 我对建议很满意 .
https://gist.github.com/Knotschi/6f97efe89681ac149113ddec4c396cc5