首页 > 解决方案 > React - 不能用作 JSX 组件。它的返回类型 'void' 不是有效的 JSX 元素

问题描述

我在这里有一个 stackblitz 演示

这是一个超级简单的应用程序,它应该只显示下面带有测试的输入以及输入字段中输入的内容的输出。

我在输入组件上遇到错误

'CustomInput' cannot be used as a JSX component.
  Its return type 'void' is not a valid JSX element.

谁能看到我为什么会收到此错误

标签: reactjs

解决方案


返回后需要加括号:

const CustomInput = ({children, value, onChange}: CustomInputProps) => {
  return (
    <div>
      <label htmlFor="search">{children}</label>
      <input id="search" type="text" value={value} onChange={onChange} />
    </div>
  )
}

https://stackblitz.com/edit/react-ts-pb6jpc?embed=1&file=index.tsx


如果你正在写作

const CustomInput = ({children, value, onChange}: CustomInputProps) => {
  return 
    <div>
      <label htmlFor="search">{children}</label>
      <input id="search" type="text" value={value} onChange={onChange} />
    </div>
}

这被转换为

const CustomInput = ({children, value, onChange}: CustomInputProps) => {
  return;
    <div>
      <label htmlFor="search">{children}</label>
      <input id="search" type="text" value={value} onChange={onChange} />
    </div>
}

所以你的函数基本上返回undefined并被解释为

const CustomInput = ({children, value, onChange}: CustomInputProps) => {
  return undefined;
  // nothing after return counts
}

推荐阅读