我有点不确定我应该如何为组件内的类型检查添加道具。到目前为止,这是我的组件:
import * as React from 'react';
import { connect } from 'react-redux';
export namespace CalculatorDisplay {
export interface Props {
display: object,
calculatorDisplay: string,
}
export interface State {
}
}
// TODO: How do we get displayString to be properly recognized in props validation?
export default class CalculatorDisplay extends React.Component<CalculatorDisplay.Props, CalculatorDisplay.State> {
render() {
let calculatorDisplay = this.props.display.displayString;
return (
<div className="display">
<div className="displayText">
{ calculatorDisplay }
</div>
</div>
)
}
}
我到达的错误是:
ERROR in [at-loader] ./src/components/CalculatorDisplay.tsx:23:48
TS2339: Property 'displayString' does not exist on type 'object'.
ERROR in [at-loader] ./src/containers/App.tsx:22:24
TS2322: Type '{ display: any; }' is not assignable to type 'IntrinsicAttributes & IntrinsicClassAttributes<CalculatorDisplay> & Readonly<{ children?: ReactNo...'.
Type '{ display: any; }' is not assignable to type 'Readonly<Props>'.
Property 'calculatorDisplay' is missing in type '{ display: any; }'.
我理解(我认为)TS正在尝试验证比对象的数据类型更具体的东西(可能是实际的状态对象本身?)。
我似乎能够让这个错误不被抛出的唯一方法是将显示设置为&#39; any&#39;但这并没有给我们任何实际细节。
我的另一个假设是我可以将calculatorDisplay独立设置为一种字符串(因为这是我们希望它返回的,最终是我关心的所有内容),这就是我上面所做的。
这是在App.tsx中使用CalculatorDisplay的方式:
import * as React from 'react'
import PropTypes from 'prop-types'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import Calculator from '../components/Calculator'
import CalculatorDisplay from '../components/CalculatorDisplay'
import * as CalculatorActions from '../actions'
import { RouteComponentProps } from 'react-router'
export namespace App {
export interface Props extends RouteComponentProps<void> {
actions: typeof CalculatorActions;
}
export interface State {
/* empty */
}
}
const App = ({todos, actions, display}) => (
<div>
<CalculatorDisplay display={display}/>
<Calculator actions={actions}/>
</div>
)
const mapStateToProps = state => ({
todos: state.todos,
display: state.numberpad
})
const mapDispatchToProps = dispatch => ({
actions: bindActionCreators(CalculatorActions as any, dispatch)
})
export default connect(
mapStateToProps,
mapDispatchToProps
)(App)
我会非常了解我是如何错误接近这一点的。谢谢。
答案 0 :(得分:1)
您需要将display
界面的props
属性设置为它的外观。看看您的redux商店中的numberpad
对象,找出display
应该是什么样子。这是我认为它应该看你的组件的方式。注意:我删除了命名空间,因为此组件中不需要它。
export interface Props {
display: {
displayString: string,
// Other properties of display go here.
};
calculatorDisplay: string;
}
export interface State {}
export default class CalculatorDisplay extends React.Component<Props, State> {
render() {
const calculatorDisplay = this.props.display.displayString;
return (
<div className="display">
<div className="displayText"> { calculatorDisplay }</div>
</div>
)
}
}