React-Native - 如何替换 react-native 核心组件的功能

React-Native - How to replace functionality of a react-native core component

我已经创建了一个 Web 应用程序,我需要将其转换为 react-native-ios 应用程序。 我为 Web 应用程序创建了一个 TextInput 小部件,它比反应本机 TextInput 组件做的更多。

  1. 如何覆盖 TextInput 的核心功能,例如 onchange 方法。

  2. 如何向 TextInput 添加额外的功能。

Web 应用程序的 TextInput 小部件是用 JavaScript 编写的。如果可能的话,我想避免 objective-C。

谢谢。

如果我没理解错的话,您不需要在这里做任何特定于 react-native 的事情。您只需使用标准的反应技术来为现有组件添加功能。因此,您可以创建一个包装 TextInput 的组件,它允许您传递 TextInput 接受的任何道具。你也可以为你的组件提供额外的道具以满足其他需求。

import * as React from 'react';
import { 
  TextInput
} from 'react-native';

class CustomInput extends React.Component {

  constructor(props) {
    this.state = {text: 'default text'}
  }

  render(): JSX.Element {

    return (
      <TextInput
        {...this.props} // pass through props
        value={this.state.text}
        onChangeText={this.onChangeText} // update value as usual
        onChange={this.props.doSomethingSpecial} // call custom prop function for custom behaviour
      />
    ); 
  }

  onChangeText = (text) => {
    this.setState({text});
  }
}

export default CustomInput;