我有一个简单的函数组件,需要使用输入引用来设置正确的提交重点:
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 一起使用仍然发出警告:
警告:不能为函数组件提供引用。尝试访问 此引用将失败。你的意思是使用 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 上尚不受支持(链接到 Github 问题(。那是在2018年,似乎到2019年5月,情况仍然相同。
如果您没有运行最新版本,您可以尝试最新版本的 React Native,看看它是否有效,如果有人可以确认这一点。
我想我解决了这个问题请参阅以下代码
应用程序.js文件:
import Input from './component/Input.js'
export default ({navigation}) => {
const inputEmail = useRef(null);
const inputPassword = useRef(null);
const updateRef = ref => {
inputPassword.current = ref.current;
};
return (
<View style={[signInScrStyle.container]}>
<Input
placeholder={'Email Address'}
onSubmitEditing={() => {
inputPassword.current.focus();
}}
updateRef={e => {
updateRef(e);
}}
ref={inputEmail}
/>
<Input
placeholder={'Password'}
onSubmitEditing={() => {
inputEmail.current.focus();
}}
updateRef={e => {
updateRef(e);
}}
ref={inputPassword}
/>
</View>
);
}
输入.js文件:
export const Input = props => {
const myRef = useRef(null);
useEffect(() => {
console.log(myRef);
props.updateRef(myRef);
return () => {};
}, []);
return (
<View style={style.txtInputContainer}>
<TextInput
style={style.txtInput}
// onChangeText={text => onChangeText(text)}
numberOfLines={1}
autoCorrect={false}
autoCapitalize={'none'}
placeholder={props.placeholder}
placeholderTextColor={'#fff'}
onSubmitEditing={() => {
props.onSubmitEditing();
}}
ref={myRef}
/>
</View>
);
}
import React from 'react'
import { View, TextInput } from 'react-native'
const usernameRef = React.createRef();
const passwordRef = React.createRef();
export default function Login() {
return (
<View style={{flex: 1 , justifyContent: "center", alignItems: "center"}}>
<TextInput ref={usernameRef} onSubmitEditing={() => passwordRef.current.focus()} placeholder="First" />
<TextInput ref={passwordRef} placeholder="second" />
</View>
)
}
小吃在这里