React Native - Доступ к методам обернутых компонентов - PullRequest
0 голосов
/ 26 сентября 2018

Я пытаюсь перенести фокус на второе поле в форме, используя пользовательские компоненты ввода.Однако я не могу получить доступ к focus() или другим методам TextInput, которые я расширяю в пользовательском классе.Я видел некоторую информацию о пересылке ссылок, а также о реализации функции focus() в классе, но пока не смог заставить ее работать.

Всякий раз, когда я пытаюсь нажать кнопку «Далее» на клавиатуре, он говорит, что фокусировка не является функцией.Буду признателен за любую помощь или ссылку.

<View>
    <CustomInput
    onRef={ref => (this.child = ref)}
    autoCapitalize={'none'}
    returnKeyType={'next'}
    autoCorrect={false}
    onSubmitEditing={() => this.lastNameInput.focus()}
    updateState={(firstName) => this.setState({firstName})}
    blurOnSubmit={false}
    />
    <CustomInput
    onRef={ref => (this.child = ref)}
    autoCapitalize={'none'}
    returnKeyType={'done'}
    autoCorrect={false}
    updateState={(lastName) => this.setState({lastName})}
    ref={(input) => { this.lastNameInput = input; }}
    onSubmitEditing={(lastName) => this.setState({lastName})}
    />
</View>
export default class UserInput extends Component {

    render() {

        return (
           <View style={styles.inputWrapper}>
            <TextInput
              style={styles.input}
              autoCorrect={this.props.autoCorrect}
              autoCapitalize={this.props.autoCapitalize}
              returnKeyType={this.props.returnKeyType}
              placeholderTextColor="white"
              underlineColorAndroid="transparent"
              onChangeText={(value) => this.props.updateState(value)}
              blurOnSubmit={this.props.blurOnSubmit}
            />
          </View>
        );
    }

}

1 Ответ

0 голосов
/ 26 сентября 2018

вам нужно сделать некоторые изменения в обоих компонентах.в соответствии с https://stackoverflow.com/a/49810837/2083099

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

class UserInput extends Component {
componentDidMount() {
    if (this.props.onRef != null) {
        this.props.onRef(this)
    }
}

onSubmitEditing() {
    if(this.props.onSubmitEditing){
        this.props.onSubmitEditing();
    }
}

focus() {
    this.textInput.focus()
}

render() {

    return (
        <View style={{ flex: 1 }}>
            <TextInput
                style={{ height: 100, backgroundColor: 'pink' }}
                autoCorrect={this.props.autoCorrect}
                autoCapitalize={this.props.autoCapitalize}
                returnKeyType={this.props.returnKeyType}
                placeholderTextColor="white"
                underlineColorAndroid="transparent"
                onChangeText={(value) => this.props.updateState(value)}
                blurOnSubmit={this.props.blurOnSubmit}
                ref={input => this.textInput = input}
                onSubmitEditing={this.onSubmitEditing.bind(this)}
            />
        </View>
    );
  }

}

export default class OrderScreen extends Component {

constructor(props) {
    super(props);

    this.focusNextField = this.focusNextField.bind(this);
    this.inputs = {};
}


focusNextField(id) {
    this.inputs[id].focus();
}

render() {
    return (
        <View style={{ flex: 1 }}>
            <UserInput
                autoCapitalize={'none'}
                returnKeyType={'next'}
                autoCorrect={false}
                updateState={(firstName) => this.setState({ firstName })}
                blurOnSubmit={false}
                onRef={(ref) => { this.inputs['projectName'] = ref; }}
                onSubmitEditing={() =>    {this.focusNextField('projectDescription');}}
            />
            <UserInput
                onRef={(ref) => {this.inputs['projectDescription'] = ref}}
                autoCapitalize={'none'}
                returnKeyType={'done'}
                autoCorrect={false}
                updateState={(lastName) => this.setState({ lastName })}
            />
        </View>
    )
 }
}
...