React - 不能用作 JSX 组件。它的返回类型“void”不是有效的 JSX 元素

lom*_*ine 15 reactjs

我这里有一个stackblitz 演示

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

我在输入组件上遇到错误

'CustomInput' cannot be used as a JSX component.
  Its return type 'void' is not a valid JSX element.
Run Code Online (Sandbox Code Playgroud)

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

str*_*605 25

return后需要添加括号:

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

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>
}
Run Code Online (Sandbox Code Playgroud)

这被转换为

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

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

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