我有一个简单的问题,我将 TypeScript
与 React
一起使用,到目前为止效果很好,但我遇到了这个小问题。我是 TypeScript
的新手,但到目前为止我很喜欢它,真的让我想起了 Go
我正在尝试创建一种样式并将其作为对象传递到样式中,例如
import * as React from 'react'
import * as ReactDOM from 'react-dom'
export interface NavbarProps {
title: string;
}
export class Navbar extends React.Component<NavbarProps, undefined> {
render() {
return (
<div style={styles.navbar}>
<div style={styles.navbarTitle}>
<h1 style={styles.navbarTitle}>{ this.props.title }</h1>
</div>
</div>
)
}
}
// Lets it compile properly
let spaceBetween: "space-between" = "space-between";
let styles = {
navbar: {
display: 'flex',
flexDirection: 'row',
paddingLeft: '10px',
paddingRight: '10px',
height: '50px',
color: 'white',
backgroundColor: "#333",
alignItems: "center",
justifyContent: spaceBetween
},
navbarTitle: {
margin: 0,
padding: 0,
letterSpacing: "1px"
}
};
如果我删除 let spaceBetween: "space-between"= "space-between"
并尝试只执行 { justifyContent: "space-between"}
我得到一个错误,因为根据 CSSProperties Interface
的类型,它声明 justifyContent
是这样的:
/**
* Defines how the browser distributes space between and around flex items
* along the main-axis of their container.
*/
justifyContent?: "flex-start" | "flex-end" | "center" | "space-between" | "space-around";
那么我怎样才能内联 justifyContent 而不是只为转换创建一个变量。
谢谢。
实际错误
src\public\views\components\navbar\navbar.tsx(11,12): error TS2322: Type '{ display: string; flexDirection: string; paddi
Types of property 'justifyContent' are incompatible.
Type 'string' is not assignable to type '"center" | "flex-start" | "flex-end" | "space-between" | "space-around"'.
最佳答案
您必须为 styles.navbar
指定正确的类型,例如
let styles = {
navbar: {
display: 'flex',
flexDirection: 'row',
paddingLeft: '10px',
paddingRight: '10px',
height: '50px',
color: 'white',
backgroundColor: "#333",
alignItems: "center",
justifyContent: "space-between"
} as ViewStyle, //<= here
...
}
关于typescript - 如何在 TypeScript 中转换对象属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41163837/