我目前正在开发一个 React Native 项目,其中我正在创建一个自定义输入组件,其中包含一个图标和一个文本输入字段。但是,当我尝试在样式表中将组件的宽度设置为“适合内容”时,我遇到了 TypeScript 的问题。
这是我的代码的简化版本:
import { View } from 'react-native';
import { createStyleSheet, useStyles } from 'react-native-unistyles';
import MyTextInput, { TextInputProps } from '../TextInput/TextInput';
import Icon from 'react-native-vector-icons/MaterialIcons';
export type IconInputProps = TextInputProps;
const stylesheet = createStyleSheet(theme => ({
iconInputWrapper: {
display: "flex",
flexDirection: "row",
alignItems: "center",
paddingHorizontal: theme.padding.base,
paddingVertical: 0,
gap: theme.gap.base,
// width: "fit-content",
},
icon: {
color: theme.colors.destructive
}
}));
export default function IconInput(props: IconInputProps) {
const { styles } = useStyles(stylesheet);
return <View style={styles.iconInputWrapper}>
<MyTextInput {...props} borderWidth={"none"} />
<Icon name='report' color={styles.icon.color} size={17} />
</View>;
};
export type TextInputProps = {
borderWidth?: keyof UnistylesTheme['borderWidth'];
borderColor?: keyof UnistylesTheme['colors'];
paddingVertical?: keyof UnistylesTheme['padding'];
paddingHorizontal?: keyof UnistylesTheme['padding'];
};
当我尝试取消注释样式表中的 width: "fit-content" 行时,问题就出现了。 TypeScript 抛出以下错误:
Types of property 'width' are incompatible.
Type '"fit-content"' is not assignable to type 'DimensionValue | { [x: symbol]: DimensionValue | undefined; landscape?: DimensionValue | undefined; portrait?: DimensionValue | undefined; } | undefined'.ts(2345)
我知道 TypeScript 期望宽度属性有一个特定的类型,但我不确定如何在这种情况下正确处理“fit-content”。有人可以提供有关如何解决此问题的指导吗?谢谢!
我创建了一个示例:
import { SafeAreaView, StyleSheet, TextInput, View } from 'react-native';
import { AntDesign } from '@expo/vector-icons';
export default function App() {
return (
<SafeAreaView style={styles.container}>
<View style={styles.textInputContainer}>
<TextInput style={styles.textInput} defaultValue={'Sample input'} />
<AntDesign style={styles.icon} name="infocirlceo" size={24} color="black" />
</View>
<View style={styles.textInputContainerSpace}>
<TextInput style={styles.textInputSpace} defaultValue={'Sample input'} />
<AntDesign style={styles.icon} name="infocirlceo" size={24} color="black" />
</View>
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#ecf0f1',
padding: 8,
},
textInput: {
backgroundColor: 'orange',
padding: 5,
flex:1
},
textInputSpace: {
backgroundColor: 'red',
padding: 5,
},
icon: {
flex:0,
},
textInputContainer: {
flexDirection: 'row'
},
textInputContainerSpace: {
flexDirection: 'row',
justifyContent: 'space-between'
},
});
让我知道这是否是想要实现的,如果不是,请创建您想要实现的绘图。