这是 react 原生问题,但类似的概念可以应用于 react 。
我想在react-native中创建一个CustomView。我正在使用 typescript 。
到目前为止,我已经:
const styles = StyleSheet.create({
container: {
backgroundColor: '#ffffff',
borderRadius: 10,
}
});
type CustomViewProps= {
width: number,
height: number,
marginTop?: string | number,
}
const CustomView = ({ width, height, marginTop }: CustomViewProps) => (
<View style={[styles.container, { height, width, marginTop }]} />
);
到目前为止,这还可以,因为只使用了 3 个属性:宽度、高度和 marginTop。
但是,这是不可重用的,如果我需要添加更多 Prop ,它可能会变得冗长。
所以,问题是:如何让 CustomView 接收到原生组件 View 可以接收的任何 props?
我的猜测是我应该删除 CustomViewProps。然后,我应该让 props 继承与原生组件 View 相同的类型。然而,我正在为此挣扎。
最佳答案
由于您正在创建 CustomViewProps
,我假设您希望在该组件已编写的行为之上向 native 组件添加一些特定行为。
让我们创建一个示例。
我想创建一个具有某些特定行为的按钮,但在其他情况下我希望它的行为类似于普通的 TouchableOpacity
组件。例如,我想添加一个“正在加载”状态,它将显示内部加载器而不是其内容。
所以逻辑是:创建自定义 Prop 并将自定义 Prop 与原生的默认 Prop 合并
import React, { FC, ReactElement } from 'react'
import { ActivityIndicator, TouchableOpacity, TouchableOpacityProps, StyleSheet } from 'react-native'
type MyProps = {
loading?: boolean
children: ReactElement
}
const MyButton: FC<MyProps & TouchableOpacityProps> = (props: MyProps & TouchableOpacityProps) => (
<TouchableOpacity {...props} disabled={props.disabled || props.loading} style={[styles.button, props.style]}>
{props.loading ? <ActivityIndicator /> : props.children}
</TouchableOpacity>
)
const styles = StyleSheet.create({
button: {
backgroundColor: 'yellow',
borderColor: 'black',
borderWidth: 1,
borderRadius: 10,
padding: 10
},
})
export default MyButton
loading
属性将负责按钮的内容或 disabled
属性。 TouchableOpacity
组件将接收每个兼容的 prop(自动建议将启用,因为您已分配了 TouchableOpacityProps
)。 styles.button
的行为类似于默认样式,但如果您在 style
属性中指定了不同的内容,则该样式将被覆盖。就是这样!
关于javascript - 创建通用自定义组件 React,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60786777/