我最近从.jsx迁移到了.tsx,我遇到了同样的问题但是,我正在正确导入PropTypes(在移动到打字稿之前,一切正常)。我怀疑有些东西与打字稿有关,但我不知道是什么。有人可以帮帮我吗?
//Board.tsx file
//Dependencies
import React, { Component } from 'react';
import PropTypes from 'prop-types';
//Components
import Button from '../components/Button';
import TaskCard from '../components/TaskCard';
//Data
import tasks from '../data/dataTasks';
import boards from '../data/dataBoards';
class Board extends Component<any, any>{
static propTypes = {
boards: PropTypes.array.isRequired,
task: PropTypes.array.isRequired
}
render(){
const { boards, task }:any = this.props;
return(
boards && boards.map(
(boards, key) =>
<div key={key} className="col-xs-3">
<div className="card">
<h4 className="card_title txt-secondary-color">{boards.name}</h4>
{
//Chequeo si existen tasks para cada board, sino muestro mensaje
tasks.filter(task => task.board == boards.id).length!=0 ?(
<div className="card_container_items">
{/* Filtro los tasks que coincidan con el board actual */}
<TaskCard tasks={tasks.filter(task => task.board == boards.id)}/>
</div>
): (
<div className="v-padding v-margin center-align">
<p className="txt-tertiary-color">Aún no tenés tareas {boards.advice}.</p>
</div>
)
}
<div className="card_actions row no-margin">
<Button text="Nuevo" icon="+" classNameCustom="btn_primary" />
</div>
</div>
</div>
)
)
}
}
export default Board;
答案 0 :(得分:0)
您尚未正确导入PropTypes模块,因为它没有默认导出,您需要使用*
导入它以相同的命名空间方式访问它
import * as PropTypes from 'prop-types'
如果您没有安装类型,则需要将其类型添加到项目中
npm install -D @types/prop-types
就个人而言,虽然我发现不必在打字稿项目中使用PropTypes,因为你应该输入你的道具界面,所以实际运行时检查很有用的情况很少,因为大多数问题都会被编译器在它进入浏览器之前。例如......
export interface IBoard {
// your board properties type defs
}
export interface ITask {
// task property type defs
}
export interface IBoardProps {
boards: IBoard[] // a required array of IBoard objects
task: ITask // a required ITask object
}
// the type `P` passed to `Component<P>` tells the compiler what type of `this.props` must be
class Board extends Component<IBoardProps>{
// no need for `static propTypes`
// as compiler knows and checks type of supplied props
// and also if required props are missing
// and won't compile if they are incorrectly implemented
render() {
const {boards, task} = this.props // don't type these as `any`, the compiler will infer their actual type from the props
// ... now you code is type safe from here, as types are inferred
}
}
export default Board