[英]How to Focus TextInput in React Native Android
I have created floatingLabelInputFocus.js
我创建了
floatingLabelInputFocus.js
import React, { Component } from 'react';
import { View, Text, TextInput} from 'react-native';
export default class FloatingLabelInputFocus extends Component {
state = {
isFocused: false,
};
handleFocus = () => this.setState({ isFocused: true });
handleBlur = () => this.setState({ isFocused: false });
render() {
const { label, ...props } = this.props;
const { isFocused } = this.state;
const labelStyle = {
position: 'absolute',
left: 0,
top: (!isFocused&&props.value==="") ? 5 : 0,
fontSize: !isFocused ? 25 : 20,
color: !isFocused ? '#aaa' : '#000',
};
return (
<View style={{ paddingTop: 10}}>
<Text style={labelStyle}>
{label}
</Text>
<TextInput
ref={(r) => this.props.onRef(r)}
{...props}
style={{ height: 50, fontSize: 25, color: '#000', borderBottomWidth: 1, borderBottomColor: '#555', marginTop:25 }}
onFocus={this.handleFocus}
onBlur={this.handleBlur}
/>
</View>
);
}
}
And I am using is as我使用的是
<FloatingLabelInputFocus
onRef={(r) => this.myField2 = r}
label="SKID CODE"
value={this.state.itemCode}
onKeyMultipleListener={() => alert('Keyboard Hidden')}
onChangeText={text => this.setState({ itemCode: text })}
/>
I have the reference of TextInput as this.myField2
.我将 TextInput 的引用作为
this.myField2
。
However, when I do this.myField2.focus()
in componentDidMount(){this.myField2.focus()}
It doesn't work.但是,当我在
componentDidMount(){this.myField2.focus()}
执行this.myField2.focus()
,它不起作用。 What is the correct way to focus TextInput?聚焦 TextInput 的正确方法是什么?
UPDATE:更新:
I found the issue is with when I go to the next page and come back the focus is not working.我发现问题在于当我转到下一页并返回时焦点不起作用。 At this time the componentDidMount() , render(), componentDidUpdate() methods are not called.
此时 componentDidMount() 、 render() 、 componentDidUpdate() 方法不会被调用。
navigate('ProcessItem', { user });
in 'ProcessSkid'
and from 'ProcessItem'
I am doing在
'ProcessSkid'
和'ProcessItem'
我正在做
const navigate = navigation.navigate;
const user = navigation.getParam('user', {});
navigate('ProcessSkid', { user });
At this time the TextInput is not focused.此时 TextInput 未聚焦。
It's because when you navigate to another component react-navigation doesn't unmount the component you were on, that's why it doesn't call componentDidMount
.这是因为当您导航到另一个组件时 react-navigation 不会卸载您所在的组件,这就是它不调用
componentDidMount
的原因。
Theres many ways to solve this有很多方法可以解决这个问题
Add listeners:添加监听器:
<NavigationEvents
onWillFocus={payload => console.log('will focus',payload)}
onDidFocus={payload => console.log('did focus',payload)} //
onWillBlur={payload => console.log('will blur',payload)}
onDidBlur={payload => console.log('did blur',payload)}
/>
OR或者
this.props.navigation.addListener('didFocus', payload=>{console.log(payload)})
And if you're using react-navigation
V5 you can use this .如果您使用的是
react-navigation
V5,则可以使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.