我有一个简单的功能组件,需要使用输入引用才能设置正确的提交焦点:
import React, { useRef } from 'react'
import { View, TextInput } from 'react-native'
export default function Login() {
let usernameRef = useRef(null)
let passwordRef = useRef(null)
return (
<View>
<TextInput ref={usernameRef} />
<TextInput ref={passwordRef} />
</View>
)
}
问题在于,将 ref 与新的 Hooks API 一起使用仍然会发出警告:
Warning: Function components cannot be given refs. Attempts to access this ref will fail. Did you mean to use React.forwardRef()?
我不想使用类。尝试使用“forwardRef”,警告仍然存在:
import React, { createRef, forwardRef } from 'react'
import { View, TextInput } from 'react-native'
export default function Login() {
let usernameRef = createRef()
let passwordRef = createRef()
const Input = forwardRef((props, ref) => (
<TextInput ref={ref} {...props} />
))
return (
<View>
<Input ref={usernameRef} />
<Input ref={passwordRef} />
</View>
)
}
我做错了什么?
最佳答案
不幸的是,React Native ( link to Github issue ) 尚不支持这一点。那是2018年的事了,看来到了2019年5月,情况还是一样。
如果您没有运行最新版本,您可以尝试最新版本的 React Native,看看它是否有效,是否有人可以确认。
关于reactjs - React Native - 函数组件上的 useRef 警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56395647/