[英]TypeScript. Assign JSX element to variable
I have a very simple function that returns an input and its value.我有一个非常简单的函数,它返回一个输入及其值。 The problem is that I don't know how to assign the JSX element to a variable.
问题是我不知道如何将 JSX 元素分配给变量。 When using usual React, everything is fine, but with TypeScript, i have an error.
当使用通常的 React 时,一切都很好,但是使用 TypeScript,我有一个错误。 Here is the function itself:
这是函数本身:
export const useInput = () => {
const [val, setInputValue] = React.useState("");
const inputValueHandler = (e: React.FormEvent<HTMLInputElement>) => {
const currentTarget = e.target as HTMLInputElement;
setInputValue(currentTarget.value);
};
const input: JSX.Element = <input value={val} onChange={inputValueHandler}/>;
return [val, input];
}
error appears here错误出现在这里
const input: JSX.Element = <input value={val} onChange={inputValueHandler}/>;
an error一个错误
"input" refers to a value, but is used as a type here. Did you mean "typeof input"?ts(2749)
The problem is that you're not telling TypeScript that that code uses JSX, so it thinks the <input ...
is the beginning of a type assertion (the angle bracket kind, not the as
kind).问题是您没有告诉 TypeScript 该代码使用 JSX,因此它认为
<input ...
是类型断言的开始(尖括号类型,而不是as
类型)。 ( Playground link to the error with the playground configured not to allow JSX.) ( 游乐场链接到错误,游乐场配置为不允许 JSX。)
If you tell TypeScript that that code is JSX (for instance, by putting it in a .tsx
file), it works just fine.如果您告诉 TypeScript 该代码是 JSX(例如,通过将其放在
.tsx
文件中),它就可以正常工作。 ( Playground example showing no error when the playground is set to support JSX.) (当 Playground 设置为支持 JSX 时, Playground 示例显示没有错误。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.