【问题标题】:Type 'Element[]' is not assignable to type 'ReactElement<any>'类型 'Element[]' 不可分配给类型 'ReactElement<any>'
【发布时间】:2018-12-09 00:31:59
【问题描述】:

我正在尝试将这个简单的 div 添加到我的 .tsx 文件的返回块中:

<div id="bizible.reportUser" style="display:none" data-email="some@email.com"/>

我是这样做的:

import React from 'react';
import Radium from 'radium';

import Icon from './Icon';
import Header from './Header';

import Colors from '../colors';

const NoMatch = ({ children, title, icon, kind }) => {
  return ([
    <div style={[styles.base, kind && styles[kind]]}>
      <Icon name={icon} style={[styles.icon]} height="48" width="48" />
      <Header title={title} style={[styles.header]} />
      <p style={[styles.message]}>
        {children}
      </p>
    </div>,
    <div id="bizible.reportUser" style="display:none" data-email="some@email.com"/>
  ]
  );
};

但是它返回一个错误消息并且不编译:

error TS2322: Type '({children, title, icon, kind}: { children: any; title: any; icon: any; kind: any; }) => Element[]' is not assignable to type 'StatelessComponent<Props>'.
  Type 'Element[]' is not assignable to type 'ReactElement<any>'.
    Property 'type' is missing in type 'Element[]'.

【问题讨论】:

  • 您正在返回一个数组。如果您只保留(),它是否有效?即从([ ... ])()
  • 不,不是@Tholle。它需要一个数组,否则你会得到这个错误:“JSX 表达式必须有一个父元素。”
  • 这听起来不对。例如。 the way stateless components are written here 工作正常。
  • 最新版本的 Reacts 显然需要数组表示法:stackoverflow.com/questions/48886726/…
  • 不,我要返回两个 div。但是,这并不能解决问题

标签: css reactjs dom tsx


【解决方案1】:

您始终可以使用&lt;React.Fragment&gt;(或&lt;&gt;)包装返回值。这将在不向 DOM 中添加任何内容的情况下解决您的问题。

【讨论】:

    猜你喜欢
    • 2022-08-04
    • 2022-12-13
    • 2017-06-21
    • 1970-01-01
    • 1970-01-01
    • 2017-08-12
    • 2021-09-23
    • 2020-08-24
    • 1970-01-01
    相关资源
    最近更新 更多