我在我的React Native应用程序中有一个屏幕,其中有几个文本字段。
我想知道是否有任何方法,在屏幕加载时我的光标自动打开并聚焦于我的第一个文本输入字段?
我正在寻找类似于Android中的stateAlwaysVisible
的东西。
我在我的React Native应用程序中有一个屏幕,其中有几个文本字段。
我想知道是否有任何方法,在屏幕加载时我的光标自动打开并聚焦于我的第一个文本输入字段?
我正在寻找类似于Android中的stateAlwaysVisible
的东西。
当<TextInput />
聚焦时,键盘应该自动打开。您可以使用autoFocus
属性使其在元素挂载时获得焦点(链接)
这个技巧对我起作用了
setTimeout(() => InputRef.current.focus(), 100)
我的方式(在组件渲染时出现聚焦和显示键盘的问题)
import { InteractionManager, TextInput } from 'react-native';
...
inputRef = React.createRef();
componentDidMount() {
this.focusInputWithKeyboard()
}
focusInputWithKeyboard() {
InteractionManager.runAfterInteractions(() => {
this.inputRef.current.focus()
});
}
render() {
<TextInput ref={this.inputRef} />
}
另一种解决方案 :)
import React, { useRef } from 'react'
export function mycomponent(props) {
const inputRef = useRef();
return(
<TextInput
ref={inputRef}
onLayout={()=> inputRef.current.focus()}>
</TextInput>
)
}
onLayout
没有被调用! - Cagri Uysal对我来说有效。
<TextInput
autoFocus={false}
autoCapitalize="none"
onChangeText={(val) => {
props.onChange(val);
}}
value={null}
defaultValue={props.defaultValue}
ref={(ref) => {
if( ref !== undefined && ref && !ref.isFocused() ){
ref.focus();
}
}}
{...propsMerge}
/>
import { StyleSheet, Text, View, TextInput } from "react-native";
import React from "react";
const HomeScreen = () => {
const inputRef = React.useRef();
setTimeout(() => inputRef.current.focus(), 100);
return (
<View style={{ paddingVertical: 20 }}>
<Text>circle</Text>
<TextInput ref={inputRef} />
</View>
);
};
export default HomeScreen;
const styles = StyleSheet.create({});
setTimeOut
用 useEffect
包装起来,否则它会在每次渲染时都被创建! - Cagri UysalsetTimeout
不是一个钩子,它只是一个JS函数。
2)你需要用useEffect
钩子包装它,就像之前说的那样。
3)当组件卸载时,最好取消它(在useEffect
的最后返回一个清理函数),像下面这样:useEffect(() => {
const timeout = setTimeout(() => inputRef.current.focus(), 100);
return () => { clearTimeout(timeout) }
}, [])
- undefined这在我的模拟器上似乎可以工作。尚未在真实设备上确认。
constructor(props) {
super(props);
this.buildNameTextInput = React.createRef();
}
<TouchableOpacity
style={styles.mainButton}
onPress={() => {
this.buildNameTextInput = true
this.props.setSaveBuildModal(true)
}}
>
<Text style={styles.mainButtonText}> Save Build </Text>
</TouchableOpacity>
<TextInput
autoFocus={!!this.buildNameTextInput}
ref={this.buildNameTextInput}
placeholder="Type a Name"
autoCapitalize="words"
style={{...styles.heroBtnText, marginVertical: 50}}
onChangeText={buildName => this.props.setCurrentBuildName(buildName)}
value={this.props.buildName}
/>
你可以将 TextInput 的引用存储为textInputRef,然后使用 this.textInputRef.focus()。
由于堆栈导航的问题(请参见所选解决方案上“SoundStage”的评论),所选解决方案对我无效。
我添加了一个名为openTheKeyboard
的新变量,最初将其设置为false
。
我的临时解决方案:
componentDidMount() {
this.setState({ openTheKeyboard: true });
}
componentDidUpdate() {
if (this.state.openTheKeyboard) {
this.textInput.focus();
this.setState({ openTheKeyboard: false });
}
}
.focus()
时键盘没有显示出来,可能的原因是什么? - Mayoul