我在React Native应用程序中使用Redux Form(RF) . 一切正常但我无法弄清楚如何从 Field 输入获取 refs
以使用Redux Form转到下一个输入字段 .
没有RF this解决方案可以正常工作 .
这是我的代码:
class RenderInput extends Component {
const { input, nextField, refs,
meta: { touched, error, warning },
input: { onChange } } = this.props
render() {
return (
<Input
returnKeyType = {'next'}
onChangeText={onChange}
onBlur={input.onBlur}
onFocus={input.onFocus}
onSubmitEditing = {(event) => {
// refs is undefined
refs[nextField].focus()
}}/>
)
}
}
class Form extends Component {
render() {
return (
<Field
name="field1"
focus
withRef
ref='field1'
nextField = "field2"
component={RenderInput}/>
<Field
name="vendor"
withRef
ref="field2"
nextAction = "field3"
component={RenderInput}/>
)
}
}
我将属性 nextField
传递给组件,以便在单击键盘上的 Next
键时确定下一个输入字段,但我无法在 RenderInput
组件中获取 refs
属性 .
知道如何获得 refs 属性吗?
4 回答
对于正在使用Redux Form React Native Elements的人,只需按照@Thomas Dittmar回答,并将以下道具添加到'FormInput'组件:
textInputRef={refField}
最新版本的React Native Element添加了focus()方法,因此您不必担心这一点 .
不推荐使用
withRef
,而是使用forwardRef
.此解决方案将道具从
Form
组件传递到RenderInput
组件并传递函数回调 .这是代码:
那么这里发生了什么?
我使用
ref={(componentRef) => this.field1 = componentRef}
将ref指定给本地作用域,如@Ksyqo建议的那样 . 谢谢你的提示 .我将
refField="field1"
传递给RenderInput并将值赋给输入ref属性ref = {refField}
. 这会将输入对象添加到refs属性 .我在Field中分配了一个
onEnter
函数我将函数传递给RenderInput的props并将其分配给
onSubmitEditing={onEnter}
函数 . 现在我们将两个函数绑定在一起 . 这意味着如果调用onSubmitEditing
,也会调用onEnter
函数最后,参考本地字段
field2
,获取渲染的Component并使用我们在Input
字段中指定的refs来设置焦点 . this.field2.getRenderedComponent().refs.field2.focus()我不知道这是否是最优雅的解决方案,但它有效 .
我努力得到一个对我有用的参考 .
现在访问像这样的实例函数 .