React-Native TypeScript:将变量传递给样式表对象时出错

问题描述 投票:0回答:1

这是我正在使用的样式以及如何使用它

style={styles.input(isPasswordSelected)}

const styles = StyleSheet.create({
  input: (isPasswordSelected: boolean) => ({
    height: 40,
    marginHorizontal: 20,
    marginVertical: 7,
    padding: 10,
    borderRadius: 10,
    backgroundColor: '#c9c9c9',
    borderWidth: 1,
    borderColor: isPasswordSelected ? '#458ae6' : 'transparent',
  }),
});

这通常在 JS 中工作没有问题,但在 ts 中我收到此错误

输入 '(isPasswordSelected: boolean) => { height: number;水平边距:数字;垂直边距:数字;填充:数字;边框半径:数字;背景颜色:字符串;边框宽度:数字;边框颜色:字符串; }' 不可分配给类型 'ViewStyle |文本样式 |图像样式'.ts(2322)

它似乎认为整个函数就是我的类型声明。

错误仅出现在 IDE 中,代码运行正常。可能可以通过更新我的 tsconfig.json 来解决

我尝试将打字更改为样式打字,但无法消除错误

typescript react-native stylesheet
1个回答
0
投票

你不能在样式表创建器中使用函数..

你可以尝试这样的事情

https://codesandbox.io/s/competent-tristan-q85jqk

import * as React from "react";
import { TextStyle, ViewStyle, View, Text, StyleSheet, TextInput } from "react-native";

const styles = StyleSheet.create<StyleSheet.Styles>({
  input: {
    height: 40,
    marginHorizontal: 20,
    marginVertical: 7,
    padding: 10,
    borderRadius: 10,
    backgroundColor: '#c9c9c9',
    borderWidth: 1,
    borderColor: 'transparent',
  },
  inputIsPasswordSelected: {
    borderColor: '#458ae6',
  },
  container: {
    flex: 1, 
    backgroundColor: "#ccc",
    justifyContent: "center",
    alignItems: "center"
  }
});

const input = (isPasswordSelected : boolean) => {
  return isPasswordSelected ? StyleSheet.flatten([styles.input, styles.inputIsPasswordSelected]) : styles.input
};

function App() {
  const [isPasswordSelected, setIsPasswordSelected] = React.useState(false)
  return (
    <View style={styles.container}>
      <Text>React Native App</Text>
      <TextInput  secureTextEntry={true} style={input(isPasswordSelected)} value="abc" />

   </View>
  );
}

export default App;
© www.soinside.com 2019 - 2024. All rights reserved.