React Native - 如何在单击文本时使用ref将焦点设置为输入

问题描述 投票:0回答:3

这是我正在做的事情:

export default class myComponent extends Component {
    render() {
        return (
            <View>
                 <Text onPress={() => {this.input.focus()}}>Click Me</Text>
                 <Input ref={input => { this.input = input}}/>
            </View>
        )
    }
}

我正在使用基于本机的组件......不确定这是否会影响这一点。当我按下文本组件时,我收到一个错误说明:_this2.input.focus is not a function. (In '_this2.input.focus()', '_this2.input.focus' is undefined)

react-native native-base
3个回答
2
投票

我不使用native-base,但正常情况下它应该是这样的:

import * as React from 'react';
import { Text, View, StyleSheet, TextInput, Dimensions } from 'react-native';
import { Constants } from 'expo';

const { width, height } = Dimensions.get('window');

export default class App extends React.Component {
  render() {
    return (
      <View style={styles.container}>
        <Text onPress={() => {this.input.focus()}}>Click Me</Text>
        <TextInput style={styles.input} ref={input => { this.input = input}}/>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingTop: Constants.statusBarHeight,
    backgroundColor: '#ecf0f1',
  },
  input: {
    backgroundColor: '#bbb',
    width: width - 40,
    height: 40,
    paddingHorizontal: 10,
    paddingVertical: 5,
  }
});

你可以在这里看到小吃:https://snack.expo.io/@gasparteixeira/inputfocus


0
投票
export default class myComponent extends Component {
  public textInput: TextInput | null = null;

  render() {
    return (
        <View>
             <Text onPress={() => {this.textInput.focus()}}>Click Me</Text>
             <TextInput ref={input => (this.textInput = input as any)}/>
        </View>
    );
  }
}

0
投票
export default class myComponent extends Component {
    render() {
        return (
            <View>
                 <Text onPress={() => {this.input.focus()}}>Click Me</Text>
                 <Input ref={ref => (this.textinput= ref)}/>
            </View>
        )
    }
}

并使用这个:

handleTextInput = () => {
    this.textinput....
 };
© www.soinside.com 2019 - 2024. All rights reserved.