首页 > 解决方案 > 自定义组件中的道具 React native + Typescript

问题描述

我在自定义组件中访问 onChangeText 时遇到问题。这是我的组件的代码:

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

type Props=
{
   style:any
   
}

const Input = (props:Props) =>
{
    return <TextInput {...props} style = {{...styles.input, ...props.style}} blurOnSubmit autoCorrect = {false} keyboardType = "number-pad" maxLength = {2} />
}

const styles = StyleSheet.create({
    
    input:{
        height:30,
        borderBottomColor: 'grey',
        borderBottomWidth: 1,
        marginVertical: 10
    }
        

})

export default Input;`

这是我正在使用的另一个文件中的代码部分:

 <Input style = {styles.input} onChangeText = {numberInputHandler} value = {enteredValue} />

OnChangeText 带有下划线,错误是“IntrinsicAttributes & Props”类型上不存在属性“onChangeText”。我在一个教程中看到,在我的自定义组件中键入 {...props} 后,可以访问它的 props,但是家伙正在用 js 编写,而我在 ts 中。感谢帮助!

标签: typescriptreact-nativereact-native-androidreact-native-textinputreact-native-component

解决方案


您的Input组件将其所有道具传递到底层TextInput,因此您可能希望它接受它TextInput所做的所有道具。现在它只接受道具style,因为这是Props.

你想要的道具是从 react-native 导出的TextInputProps,所以你可以导入它interface

import { TextInput, TextInputProps, StyleSheet } from "react-native";

TextInputProps已经包含一个style类型比您的更准确的属性any,因此您可以完全删除您的Props界面。

const Input = (props: TextInputProps) => {

现在在组合这两种样式时会出现错误,因为props.style可能是样式数组。使用 react-native,您可以将多个样式连接到一个数组中,即使这些样式本身可能是一个数组。所以你可以像这样组合:

style={[styles.input, props.style]}

由于我们允许所有的,如果你用 withTextInputProps调用你就不会出错。现在,由于顺序,该道具将被忽略和覆盖——后来的道具覆盖了之前的道具。如果这是您想要的,那么这个组件就可以了:Input<Input maxLength={5}/>maxLengthmaxLength={2}

const Input = (props: TextInputProps) => {
  return (
    <TextInput
      {...props}
      style={[styles.input, props.style ]}
      blurOnSubmit
      autoCorrect={false}
      keyboardType="number-pad"
      maxLength={2}
    />
  );
};

如果您希望自定义道具覆盖默认道具,那么您需要更改顺序:

const Input = (props: TextInputProps) => {
  return (
    <TextInput
      blurOnSubmit
      autoCorrect={false}
      keyboardType="number-pad"
      maxLength={2}
      {...props}
      style={[styles.input, props.style]}
    />
  );
};

推荐阅读