繁体   English   中英

如何在 React Native Android 中聚焦 TextInput

[英]How to Focus TextInput in React Native Android

我创建了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>
        );
    }
}

我使用的是

  <FloatingLabelInputFocus
                    onRef={(r) => this.myField2 = r}
                    label="SKID CODE"
                    value={this.state.itemCode}
                    onKeyMultipleListener={() => alert('Keyboard Hidden')}
                    onChangeText={text => this.setState({ itemCode: text })}
                />

我将 TextInput 的引用作为this.myField2

但是,当我在componentDidMount(){this.myField2.focus()}执行this.myField2.focus() ,它不起作用。 聚焦 TextInput 的正确方法是什么?

更新:

我发现问题在于当我转到下一页并返回时焦点不起作用。 此时 componentDidMount() 、 render() 、 componentDidUpdate() 方法不会被调用。

navigate('ProcessItem', { user });
'ProcessSkid''ProcessItem'我正在做

const navigate = navigation.navigate; 
const user = navigation.getParam('user', {}); 
navigate('ProcessSkid', { user });



此时 TextInput 未聚焦。

这是因为当您导航到另一个组件时 react-navigation 不会卸载您所在的组件,这就是它不调用componentDidMount的原因。

有很多方法可以解决这个问题

添加监听器:

<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)}
/>

或者

this.props.navigation.addListener('didFocus', payload=>{console.log(payload)})

如果您使用的是react-navigation V5,则可以使用

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM