如何将下一个输入字段集中在react-native组件

时间:2018-04-09 10:37:30

标签: reactjs react-native input components focus

我有一个名为ImageTextField的组件:

import React from 'react';
import {TextInput, View } from 'react-native';

export default class ImageTextField extends React.Component {
  render() {
    const {
      placeHolderValue, value, editable
    } = this.props;
    return (
      <View>
        <TextInput
          placeholder={placeHolderValue}
          placeholderTextColor="#b1b1b1"
          value={value}
          editable={editable}
        />
      </View>
    );
  }
}

我的屏幕:

import React from 'react';
import { StyleSheet, View, Text, TouchableOpacity} from 'react-native';
import ImageTextField from '../../custom-elements/ImageTextField';

export default class App extends React.Component {
  render() {
    return (
      <ImageTextField 
        onChangeText={text => this.onNameChange(text)}
        color={Colors.textFieldBlack}
        placeHolderValue="Name"
        value={this.state.name}
        autoCapitalize="words"
      />
      <ImageTextField
        onChangeText={text => this.onEmailChange(text)}
        color={Colors.textFieldBlack}
        placeHolderValue="E-mail"
        value={this.state.email}
        keyboardType='email-address'
      />
      <ImageTextField
        onChangeText={text => this.onPhoneChange(text)}
        color={Colors.textFieldBlack}
        placeHolderValue="Phone"
        value={this.state.phone}
        keyboardType="phone-pad"
      />
    );
  }
}

在上面的代码中,我有我在屏幕上使用的ImageTextField组件,我想聚焦下一个字段,如果用户按下键盘中的下一个键,则需要跳到第二个字段。

2 个答案:

答案 0 :(得分:3)

添加一个prop,它将检索ImageTextField组件的输入的ref。所以你的渲染函数应该如下所示:

Availabilities

然后您的App组件将如下所示:

render() {
const {
  placeHolderValue, value, editable, inputRef
} = this.props;
return (
  <View>
    <TextInput
      placeholder={placeHolderValue}
      placeholderTextColor="#b1b1b1"
      value={value}
      editable={editable}
      ref={inputRef}
    />
  </View>
);
}

答案 1 :(得分:0)

Component Name = MyTextInput

render() {
return (
<View>
<TextInput
  onChangeText={this.props.onChangeText}
  placeholder="some text"
  value={this.state.value}
  ref={this.props.inputRef}
  onSubmitEditing={this.props.onSubmitEditing}
/>
  </View>
);
}

然后您的App组件将如下所示:

<MyTextInput 
    onChangeText={text => this.onNameChange(text)}
    color={Colors.textFieldBlack}
    placeHolderValue="Name"
    value={this.state.name}
    autoCapitalize="words"
    onSubmitEditing={() => this.email.focus()}
  />

  <MyTextInput 
    onChangeText={text => this.onNameChange(text)}
    color={Colors.textFieldBlack}
    placeHolderValue="email"
    value={this.state.name}
    autoCapitalize="words"
    inputRef={ref => this.email = ref}
    onSubmitEditing={() => alert('submitted')}
  />