首页 文章

如何在react中通过包装类公开内部组件的功能?

提问于
浏览
0

我正在使用@ shoutem / ui库,它具有自己的TextInput实现,用于本机响应 .

https://github.com/shoutem/ui/blob/develop/components/TextInput.js

我正在尝试将焦点设置在键盘上的下一个输入按下按钮,就像这样

React Native: How to select the next TextInput after pressing the "next" keyboard button?

但是,Shoutem / ui的实现没有公开我可以从引用中使用的TextInput的focus()方法 .

如何将TextInput的focus方法公开为外部类中的属性?

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

import { connectStyle } from '@shoutem/theme';
import { connectAnimation } from '@shoutem/animation';

class TextInput extends Component {
  focus() {
     // how do I expose the react native text input focus method from this class?  
     // do I get a reference to the text input component somehow?
  }
  render() {
    const { props } = this;
    const style = {
      ...props.style,
    };
    delete style.placeholderTextColor;
    delete style.selectionColor;

    return (
      <RNTextInput
        {...props}
        style={style}
        placeholderTextColor={props.style.placeholderTextColor}
        selectionColor={props.style.selectionColor}
      />
    );
  }
}

TextInput.propTypes = {
  ...RNTextInput.propTypes,
  style: React.PropTypes.object,
};

const AnimatedTextInput = connectAnimation(TextInput);
const StyledTextInput = connectStyle('shoutem.ui.TextInput')(AnimatedTextInput);

export {
  StyledTextInput as TextInput,
};

1 回答

  • 1

    你可以使用refs .

    focus() {
        this.rnInput.focus();
    }
    render() {
        const { props } = this;
        const style = {
        ...props.style,
        };
        delete style.placeholderTextColor;
        delete style.selectionColor;
    
        return (
        <RNTextInput
            {...props}
            ref={input => this.rnInput = input}
            style={style}
            placeholderTextColor={props.style.placeholderTextColor}
            selectionColor={props.style.selectionColor}
        />
        );
    }
    

    一点解释 . 在组件完成渲染之后执行ref回调,然后您可以获得该组件的当前实例的引用,您可以将其保存在变量中供以后使用 ref={input => this.rnInput = input} . 现在您可以使用 this.rnInput 来调用 focus 方法 .

相关问题