简体   繁体   English

使用 React.createElement 时对象不是有效的反应子对象?

[英]Objects are not valid react child when using React.createElement?

I have a simple text component:我有一个简单的文本组件:

import * as React from 'react'

interface IProps {
  level: 't1' | 't2' | 't3',
  size: 's' | 'm' | 'l' | 'xl' | 'xxl',
  subtle?: boolean,
  children: any,
}

const textSize = (size) => {
  if (size === 's') {
    return 'f6'
  }
  if (size === 'm') {
    return 'f5 fw3'
  }
  if (size === 'l') {
    return 'f4 fw5  lh-2'
  }
  if (size === 'xl') {
    return 'f3 fw5 lh-2 ls-025 ma0'
  }
  if (size === 'xxl') {
    return 'f2 fw5 lh-title ls-03125 ma0 mb3'
  }
}

const elements = {
  t1: 'h2',
  t2: 'h1',
  t3: 'span',
};


export const Text = ({ children, level, size, subtle, ...props }: IProps) => {
  return React.createElement(
    elements[level] || elements.t3,
    {className: textSize(size)},
    props,
    children,
  );
}

Which is used like so:像这样使用:

    <Text
      size='s'
      level={'t3'}>
        Hello world
    </Text>

However, when the line {className: textSize(size)}, is included in the main component I get the following error:但是,当行{className: textSize(size)},包含在主要组件中时,我收到以下错误:

Objects are not valid as a React child (found: object with keys {}).对象作为 React 子项无效(找到:object,键为 {})。 If you meant to render a collection of children, use an array instead.如果您打算呈现子项集合,请改用数组。 in span in Unknown`在跨度未知`

Any ideas what can cause this?有什么想法会导致这种情况吗?

Codesandbox 代码沙盒

React.createElement takes 3 arguments, and you try to pass 4. React.createElement取 3 arguments,你尝试传 4。

React.createElement(component, props, ...children) React.createElement(组件,道具,...儿童)

In your case {className: textSize(size)} becomes props , and your props is actually children .在您的情况下, {className: textSize(size)}成为props ,而您的props实际上是children You probably need to do something like你可能需要做类似的事情

return React.createElement(
    elements[level] || elements.t3,
    {...props, className: textSize(size)},
    children,
  );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM