typescript - 自定义组件中的道具 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 中。感谢帮助!
解决方案
您的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}/>
maxLength
maxLength={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]}
/>
);
};
推荐阅读
- javascript - 数组语法中的扩展运算符 Vs。大批
- java - 有没有办法同时检测按键和显示图形?
- ios - Xcode 12.4:代码签名“AAExtensions.framework”失败
- c# - 如何使用 Atata 进行基本的自动浏览器检测,然后自动设置驱动程序?我正在阅读文档,但运气不佳
- php - PHP in_array 函数找不到值
- javascript - 有没有办法在不等待的情况下检查直接调用的异步函数
- python - 类型错误:get_orders() 缺少 1 个必需的位置参数:'self' - 连接到数据库并将其转换为 panda 数据框
- xcode - ARKit(ARWorldTrackingConfiguration)定位问题
- python - 梯度下降更新的亚当优化似乎不适用于逻辑回归
- javascript - 对于多租户数据库,将租户 ID 作为 GET 参数传递给 API 是否安全?