React 组件函数返回 JSX 在 ES6 的 render 方法中使用时导致错误 class React 组件

React component function returning JSX causes error when used in render method of ES6 class React component

我有一个 returns JSX 的函数,如下所示:

  function struct(locals) { 
    return (
      <View style={fieldsetStyle}>
        {label}
        {error}
        {rows}
      </View>
    );
}
label, error, and rows are functions that also return JSX.

我在 ES6 class 组件的渲染方法中调用了这个函数

class Component extends React.Component {
  render() {
    const locals = this.getLocals();

    return struct(locals); 
  }
}

当我 运行 代码时,出现错误

元素类型无效:应为字符串(对于内置组件)或 class/function(对于复合组件)但得到:对象。检查渲染 Struct

的方法

如何从结构函数中获取结果以呈现为组件 class 呈现的 return 值?

您返回的是 React 组件,而不是 React 元素。区别在于元素描述了如何创建组件,而组件是实例化的 class。您需要return React.createElement(Struct);,或return <Struct/>。此外,您的 locals 变量实际上是一个 props 对象。所以你的代码应该是这样的:

function struct({locals}) { 
    return (
      <View style={fieldsetStyle}>
        {label}
        {error}
        {rows}
      </View>
    );
}

class Component extends React.Component {
  render() {
    const locals = this.getLocals();

    return <Struct locals={locals}/>; 
  }
}

首先,您必须将该函数作为 ES 模块导入到您的 class 组件中。

import { struct } from '..path/to/struct';

然后你的渲染函数应该 return 一些 JSX,它是语法糖。您应该将中间变量放在渲染方法中的 return 语句之前。如果您有多个元素,将它包装在 div 中会更安全。

  render() {
    const locals = this.getLocals();
    return (
      <div>
        struct(locals);
      </div>
    );
  }