Type ‘Element’ is not assignable to type ‘string’ in .tsx file.

huangapple go评论63阅读模式
英文:

Type 'Element' is not assignable to type 'string' in .tsx file

问题

我有这个问题要在 tsx 文件中添加表单元素。

import { AuthLayout } from "../layout/AuthLayout"

export const LoginPage = () => {
  return (
    <AuthLayout title='Login'>
      <form>
        // 这里添加表单元素
      </form>
    </AuthLayout>
  )
}

图像描述在这里

英文:

I have this problem to add form element in tsx file.

import { AuthLayout } from &quot;../layout/AuthLayout&quot;

export const LoginPage = () =&gt; {
       return (
      &lt;AuthLayout title=&#39;Login&#39;&gt;

        &lt;form&gt;
          
          bla bla bla

        &lt;/form&gt;

      &lt;/AuthLayout&gt;
    ) }

enter image description here

答案1

得分: 1

错误消息告诉您,AuthLayout组件期望的子元素类型为string,但您传递了一个form

您应该进行更灵活的更改,以使子元素不仅接受字符串,还可以接受(单个或多个)HTML元素和React组件。您可以通过使用React.ReactNode来为children指定类型。

export const AuthLayout = ({
  children,
  title,
}: {
  children: React.ReactNode;
  title: string;
}) => {
  // ...
};

像您在评论中提到的那样将其类型设置为any并不建议,因为这会消除TypeScript的主要优势,即在运行时之前确保正确的类型。

英文:

The error message is telling you that the AuthLayout component is expecting a child of type string, but you're passing it a form instead.

You should change it so that children can be more flexible than that, accepting not only string but also (single or multiple) HTML element(s) and React component(s). You can do that by typing children with React.ReactNode.

export const AuthLayout = ({
  children,
  title,
}: {
  children: React.ReactNode;
  title: string;
}) =&gt; {
  // ...
};

*Typing it is as any, like you mentioned in your comment, is not recommended, as it eliminates the main advantage of TypeScript, which is ensuring correct typing during development, before runtime.

huangapple
  • 本文由 发表于 2023年2月19日 04:08:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75496094.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定