英文:
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 "../layout/AuthLayout"
export const LoginPage = () => {
return (
<AuthLayout title='Login'>
<form>
bla bla bla
</form>
</AuthLayout>
) }
答案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;
}) => {
// ...
};
*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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论