在我组件的渲染函数中,我有:

render() {
    const items = ['EN', 'IT', 'FR', 'GR', 'RU'].map((item) => {
      return (<li onClick={this.onItemClick.bind(this, item)} key={item}>{item}</li>);
    });
    return (
      <div>
        ...
                <ul>
                  {items}
                </ul>
         ...
      </div>
    );
  }

一切呈现良好,但当点击<li>元素时,我收到以下错误:

Uncaught Error: Invariant Violation: Objects are not valid as a React child (found: object with keys {dispatchConfig, dispatchMarker, nativeEvent, target, currentTarget, type, eventPhase, bubbles, cancelable, timeStamp, defaultPrevented, isTrusted, view, detail, screenX, screenY, clientX, clientY, ctrlKey, shiftKey, altKey, metaKey, getModifierState, button, buttons, relatedTarget, pageX, pageY, isDefaultPrevented, isPropagationStopped, _dispatchListeners, _dispatchIDs}). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method of Welcome.

如果我改成this。onitemclick。绑定(this, item) to (e) => onItemClick(e, item)内的映射函数,一切都按预期工作。

如果有人能解释我做错了什么,为什么我会得到这个错误,那就太好了

更新1: onItemClick函数如下所示。setState会导致错误消失。

onItemClick(e, item) {
    this.setState({
      lang: item,
    });
}

但是我不能删除这一行,因为我需要更新这个组件的状态


当前回答

只需创建一个有效的JSX元素。在我的例子中,我将一个组件分配给一个对象。

const AwesomeButtonComponent = () => <button>AwesomeButton</button>
const next = {
  link: "http://awesomeLink.com",
  text: "Awesome text",
  comp: AwesomeButtonComponent
}

在我的代码的其他地方,我想动态分配那个按钮。

return (
  <div>
    {next.comp ? next.comp : <DefaultAwesomeButtonComp/>}
  </div>
)

我通过声明一个通过props comp初始化的JSX comp来解决这个问题。

const AwesomeBtnFromProps = next.comp
return (
  <div>
    {next.comp ? <AwesomeBtnFromProps/> : <DefaultAwesomeButtonComp/>}
  </div>
)

其他回答

我只是得到了相同的错误,但由于不同的错误:我使用了双括号,如:

{{count}}

插入count的值而不是正确的值:

{count}

编译器可能将其转换为{{count: count}},即试图将一个对象作为React子对象插入。

我的问题是忘记了道具周围的花括号被发送到一个表示组件:

之前:

const TypeAheadInput = (name, options, onChange, value, error) => {

const TypeAheadInput = ({name, options, onChange, value, error}) => {

当我试图显示createdAt属性时,我得到了这个错误,这是一个日期对象。如果像这样在末尾连接. tostring(),它将执行转换并消除错误。只是把这个作为一个可能的答案,以防其他人遇到同样的问题:

{this.props.task.createdAt.toString()}

试试这个

 {items && items.title ? items.title : 'No item'}

我有同样的问题,因为我没有把道具放在花括号里。

export default function Hero(children, hero ) {
    return (
        <header className={hero}>
            {children}
        </header>
    );
}

所以如果你的代码和上面的类似,你就会得到这个错误。 要解决这个问题,只需在道具周围加上花括号。

export default function Hero({ children, hero }) {
    return (
        <header className={hero}>
            {children}
        </header>
    );
}