javascript - 将数组传递给组件时出错(React - TypeScript)

标签 javascript reactjs typescript

尝试描述组件 2 的输入,但收到错误。请告知如何正确传递和描述数组输入。

型号:

interface IIncident {
    id: string,
    title: string
}

组件 1:

interface IncidentManagerProps {
}

interface IncidentManagerState {
    incidents: IIncident[]
}

class IncidentManager extends Component<IncidentManagerProps, IncidentManagerState> {
    constructor(props: IncidentManagerProps) {
        super(props);
        this.state = {
            incidents: []
        }
    }

    render = () => {
        const {incidents} = this.state;

        return (
            <div className={'inc-cont'}>
                <p>All Incidents</p>
                <div className={'all-inc'}>

                    //Error displayed here
                    <Incidents incidents={incidents}/>
                </div>
            </div>
        );
    }
}

组件 2:任何类型的事件都可以解决问题,但这不是一个好方法

interface Incidents {
    incidents: IIncident[]
}

const Incidents = (props: Incidents) => props.incidents.map((inc: IIncident) => (
   <Incident key={inc.id} title={inc.title}/>
));

错误消息:

JSX element type 'Element[]' is not a constructor function for JSX elements.
  Type 'Element[]' is missing the following properties from type 'Element': type, props, key  TS2605

最佳答案

render() 不能返回元素数组,只能返回单个元素。尝试将第二个组件输出包装到任何元素,如下所示:

const Incidents = (props: {incidents: IIncident[]}) => <>
  {props.incidents.map(inc =>
    <Incident key={inc.id} title={inc.title}/>
  )}
</>;

关于javascript - 将数组传递给组件时出错(React - TypeScript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58361984/

相关文章:

javascript - 在javascript类中创建方法事件

javascript - Typescript:类型 'Promise<{}>' 无法分配给类型

javascript - 如何通过 javascript 从管理页面检索 Django 模型 ID

javascript - Github - 读取边带数据包时意外断开连接

Javascript 替换正则表达式除 p、a 和 img 之外的所有 html 标签

javascript - 何时应用动态样式表?

javascript - 获取javascript对象中的最后一项

javascript - 在 TypeScript 中使用 Angular $httpProvider

typescript - 当它的子属性更改时强制 vue.js 刷新 Prop

javascript - react 。如何在测试中模拟 api 调用