jsx 相关问题

JSX是一种开源编程语言,或者是具有类和静态类型的AltJS。源代码被编译成高度优化的JavaScript。有关React的问题,请改用[reactjs]!

React JSX 中的动态标签名称

我正在尝试为 HTML 标题标签(h1、h2、h3 等)编写一个 React 组件,其中标题级别通过 prop 指定。 我尝试这样做: 你好 我正在尝试为 HTML 标题标签(h1、h2、h3等)编写一个 React 组件,其中标题级别是通过 prop 指定的。 我尝试这样做: <h{this.props.level}>Hello</h{this.props.level}> 我期望的输出如下: <h1>Hello</h1> 但这不起作用。 有什么办法可以做到这一点吗? 无法就地执行此操作,只需将其放入变量中(首字母大写): const CustomTag = `h${this.props.level}`; <CustomTag>Hello</CustomTag> 如果您使用 TypeScript,您会看到如下错误: Type '{ children: string; }' has no properties in common with type 'IntrinsicAttributes'.ts(2559) TypeScript 不知道 CustomTag 是有效的 HTML 标签名称,并会抛出无用的错误。 要修复,请将 CustomTag 转换为 keyof JSX.IntrinsicElements! // var name must start with a capital letter const CustomTag = `h${this.props.level}` as keyof JSX.IntrinsicElements; // or to let TypeScript check if the tag is valid // const CustomTag : keyof JSX.IntrinsicElements = `h${this.props.level}`; <CustomTag>Hello</CustomTag> 为了完整起见,如果想使用动态名称,也可以直接调用 React.createElement,而不是使用 JSX: React.createElement(`h${this.props.level}`, null, 'Hello') 这避免了创建新变量或组件。 搭配道具: React.createElement( `h${this.props.level}`, { foo: 'bar', }, 'Hello' ) 来自文档: 创建并返回给定类型的新 React 元素。类型参数可以是标签名称字符串(例如 'div' 或 'span'),也可以是 React 组件类型(类或函数)。 使用 JSX 编写的代码将转换为使用 React.createElement()。如果您使用 JSX,您通常不会直接调用 React.createElement()。请参阅 React Without JSX 了解更多信息。 所有其他答案都工作正常,但我会添加一些额外的,因为通过这样做: 比较安全一点。即使你的类型检查失败了,你仍然 返回正确的组件。 它更具声明性。任何人通过查看这个组件都可以看到它可以返回什么。 它更灵活,例如代替“h1”,“h2”,...对于您的标题类型,您可以有一些其他抽象概念“sm”,“lg”或“主要”,“次要” 标题组件: import React from 'react'; const elements = { h1: 'h1', h2: 'h2', h3: 'h3', h4: 'h4', h5: 'h5', h6: 'h6', }; function Heading({ type, children, ...props }) { return React.createElement( elements[type] || elements.h1, props, children ); } Heading.defaultProps = { type: 'h1', }; export default Heading; 你可以这样使用它 <Heading type="h1">Some Heading</Heading> 或者你可以有不同的抽象概念,例如你可以定义一个尺寸道具,如: import React from 'react'; const elements = { xl: 'h1', lg: 'h2', rg: 'h3', sm: 'h4', xs: 'h5', xxs: 'h6', }; function Heading({ size, children }) { return React.createElement( elements[size] || elements.rg, props, children ); } Heading.defaultProps = { size: 'rg', }; export default Heading; 你可以这样使用它 <Heading size="sm">Some Heading</Heading> 在动态标题 (h1, h2...) 的实例中,组件可以像这样返回 React.createElement(上面由 Felix 提到)。 const Heading = ({level, children, ...props}) => { return React.createElement('h'.concat(level), props , children) } 为了可组合性,道具和子项都被传递。 参见示例 这就是我为我的项目进行设置的方式。 排版类型.ts import { HTMLAttributes } from 'react'; export type TagType = 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6' | 'p' | 'span'; export type HeadingType = HTMLAttributes<HTMLHeadingElement>; export type ParagraphType = HTMLAttributes<HTMLParagraphElement>; export type SpanType = HTMLAttributes<HTMLSpanElement>; export type TypographyProps = (HeadingType | ParagraphType | SpanType) & { variant?: | 'h1' | 'h2' | 'h3' | 'h4' | 'h5' | 'h6' | 'body1' | 'body2' | 'subtitle1' | 'subtitle2' | 'caption' | 'overline' | 'button'; }; 版式.tsx import { FC } from 'react'; import cn from 'classnames'; import { typography } from '@/theme'; import { TagType, TypographyProps } from './TypographyType'; const headings = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']; const paragraphs = ['body1', 'body2', 'subtitle1', 'subtitle2']; const spans = ['button', 'caption', 'overline']; const Typography: FC<TypographyProps> = ({ children, variant = 'body1', className, ...props }) => { const { variants } = typography; const Tag = cn({ [`${variant}`]: headings.includes(variant), [`p`]: paragraphs.includes(variant), [`span`]: spans.includes(variant) }) as TagType; return ( <Tag {...props} className={cn( { [`${variants[variant]}`]: variant, }, className )} > {children} </Tag> ); }; export default Typography; 你可以尝试一下。我是这样实现的。 import { memo, ReactNode } from "react"; import cx from "classnames"; import classes from "./Title.module.scss"; export interface TitleProps { children?: ReactNode; className?: string; text?: string; variant: Sizes; } type Sizes = "h1" | "h2" | "h3" | "h4" | "h5" | "h6"; const Title = ({ className, variant = "h1", text, children, }: TitleProps): JSX.Element => { const Tag = `${variant}` as keyof JSX.IntrinsicElements; return ( <Tag className={cx(`${classes.title} ${classes[variant]}`, { [`${className}`]: className, })} > {text || children} </Tag> ); }; export default memo(Title); //for Typescript interface ComponentProps { containerTag: keyof JSX.IntrinsicElements; } export const Component = ({ containerTag: CustomTag }: ComponentProps) => { return <CustomTag>Hello</CustomTag>; } 概括robstarbuck的答案您可以创建一个完全动态的标签组件,如下所示: const Tag = ({ tagName, children, ...props }) => ( React.createElement(tagName, props , children) ) 你可以这样使用: const App = ({ myTagName = 'h1' }) => { return ( <Tag tagName={myTagName} className="foo"> Hello Tag! </Tag> ) } React + TypeScript 这个实现为 OP 的问题定义了一个简洁的类型安全的可组合方法。它定义了一个 props 类型,该类型将对应于任何有效标题标签的属性以及任何有效的 React 组件属性(例如 className 或 children)。此外,如果 level 的值不是预期的 1 到 6,您将收到 TypeScript 错误。它还解决了之前答案中的“联合”错误。 HeadingWithRef示例更进一步,允许父级访问生成的 DOM 属性,以防您需要对其进行动态处理或读取原始元素的属性值。 //Define the heading properties type interface HeadingProps extends React.ComponentProps<"h1" | "h2" | "h3" | "h4" | "h5" | "h6"> { level: 1 | 2 | 3 | 4 | 5 | 6; } //Define the component const Heading: React.FC<HeadingProps> = ({ level, ...props }) => { const Tag: keyof JSX.IntrinsicElements = `h${level}`; return <Tag {...props} />; }; //If you need ref forwarding const HeadingWithRef = React.forwardRef<HTMLHeadingElement, HeadingProps>( ({ level, ...props }, ref) => { const Tag: keyof JSX.IntrinsicElements = `h${level}`; return <Tag ref={ref} {...props} />; } ); HeadingWithRef.displayName = "HeadingWithRef"; 使用示例 //This will render an <h2> tag export default function DemoPage() { return ( <> <header> <Heading level={2}>Heading</Heading> </header> </> ); }

回答 10 投票 0

在登录重定向之前强制ReactJS路由索引重新评估

我希望根据用户本地存储中是否存在令牌,有条件地将经过身份验证的路由包含在我的 ReactJS 应用程序的路由索引中。然而,要实现这一点,路线...

回答 1 投票 0

当提供的文件没有标题时禁用或覆盖 jsx-a11y/media-has-caption

我有一个音频文件,我正在从内容中查询,但我没有显示数据,而是不断收到此 eslintrule 弹出窗口。 这是一个音频文件,因此没有字幕。有没有办法禁用此功能或

回答 2 投票 0

jsx-a11y/media-has-caption 的 eslint 问题

我有一个音频文件,我正在从 contentful 中查询,但我没有显示数据,而是不断收到此 eslintrule 弹出窗口,它是一个音频文件,因此没有字幕。有没有办法禁用此功能或

回答 2 投票 0

当我尝试“npx expo start -c”时出现错误

错误:使用 React Native 和 NativeWind 设置 Tailwind CSS 时,.plugins 不是有效的插件属性 问题: 我正在尝试使用 NativeWind 在我的 React Native 项目中设置 Tailwind CSS,...

回答 1 投票 0

JSX 中价差运算符的奇怪行为

JS环境下的Spread运算符 让 obj1 = {a:1,b:2} 让 obj2 = {...obj1} 控制台.log(obj2) 上面的代码输出 {a:1,b:2} 这是 obj1 的副本 JSX 中的扩展运算符 让我们假设 this.props =...

回答 2 投票 0

我无法在单元格表中动态插入 React 图标

我尝试在单元格(表格)中插入 React 图标,但收到消息 无法在“Node”上执行“appendChild”:参数 1 不是“Node”类型。 我的代码很简单: const iconCell = 行。

回答 1 投票 0

从 Checkbox 切换后 Switch 组件不工作

我之前使用 Ant Design Checkbox 来检查和发布评论,运行良好,没有错误。 我之前使用 Ant Design Checkbox 来检查和发布评论,运行良好,没有错误。 <Checkbox key={record.id} checked={Publish[record?.id]?.["ispublish"] == 'true' ? true : false} onChange={(e) => Update(e.target.checked, record)} /> 我想用 Switch 代替。 <Switch key={record.id} checked={Publish[record?.id]?.["ispublish"] == 'true' ? true : false} onChange={(e) => Update(e.target.checked, record)} /> 我收到错误: 无法读取未定义的属性(读取“已检查”) 我想要Switch工作。 onChange组件的Switch prop 回调需要 两个参数。第一个是当前 checked 值,第二个是 onChange 事件对象。 查看Switch组件API: 财产 描述 类型 onChange 当选中状态发生变化时触发 function(checked: boolean, event: Event) 与CheckBox组件API相比: 财产 描述 类型 onChange 状态改变时触发的回调函数 (e: CheckboxChangeEvent) => void 更新为使用第一个参数,checked: <Switch key={record.id} checked={Publish[record?.id]?.ispublish == 'true'} onChange={(checked) => Update(checked, record)} />

回答 1 投票 0

react 不渲染 Header.jsx 文件

[header.jsxapp.jsxre](https://i.sstatic.net/eAEmStYv.png) 你好!我第一次创建这个 React 应用程序...并且我导入/导出了应用程序文件和头文件...都在 jsx 中。 即使你...

回答 1 投票 0

没有 JSX 可以使用 React 吗?

jsx 在 React 中被战术性地使用,通过更详细地查看代码来帮助开发人员理解 React 组件。 现在的问题是,是否可以使用其他方法,例如使用简单的

回答 2 投票 0

TSX 文件类型不匹配且 key prop 不存在错误

我正在尝试创建一个简单的 next.js 应用程序并尝试生成一个表,如下所示: 界面用户{ id:号码; 名称:字符串; 电子邮件:字符串; } const UserTable = async () => { ...

回答 1 投票 0

如何添加 javascript <script> 标签代码到 React 页面

我有以下代码,它是从 Drift 生成的实时聊天小部件。 “严格使用”; !功能() { var t = 窗口。</desc> <question vote="1"> <p>我下面有以下代码,它是从 Drift 生成的实时聊天小部件。</p> <pre><code>&lt;!-- Start of Async Drift Code --&gt; &lt;script&gt; &#34;use strict&#34;; !function() { var t = window.driftt = window.drift = window.driftt || []; if (!t.init) { if (t.invoked) return void (window.console &amp;&amp; console.error &amp;&amp; console.error(&#34;Drift snippet included twice.&#34;)); t.invoked = !0, t.methods = [ &#34;identify&#34;, &#34;config&#34;, &#34;track&#34;, &#34;reset&#34;, &#34;debug&#34;, &#34;show&#34;, &#34;ping&#34;, &#34;page&#34;, &#34;hide&#34;, &#34;off&#34;, &#34;on&#34; ], t.factory = function(e) { return function() { var n = Array.prototype.slice.call(arguments); return n.unshift(e), t.push(n), t; }; }, t.methods.forEach(function(e) { t[e] = t.factory(e); }), t.load = function(t) { var e = 3e5, n = Math.ceil(new Date() / e) * e, o = document.createElement(&#34;script&#34;); o.type = &#34;text/javascript&#34;, o.async = !0, o.crossorigin = &#34;anonymous&#34;, o.src = &#34;https://js.driftt.com/include/&#34; + n + &#34;/&#34; + t + &#34;.js&#34;; var i = document.getElementsByTagName(&#34;script&#34;)[0]; i.parentNode.insertBefore(o, i); }; } }(); drift.SNIPPET_VERSION = &#39;0.3.1&#39;; drift.load(&#39;...&#39;); &lt;/script&gt; &lt;!-- End of Async Drift Code --&gt; </code></pre> <p>我正在尝试将此代码添加到 jsx 文件中。</p> <p>我尝试将上述内容直接包含到 jsx 文件中返回的内容中,但这不起作用。</p> <p>我还尝试将上述代码放入其自己的函数中,并使用 <pre><code>{{}}</code></pre> 在屏幕上应显示的内容中调用它,但这也不起作用。</p> <p>代码没有任何错误,它只在控制台中报告这一点,告诉我它刚刚被调用。 <pre><code>DRIFT_WIDGET:: widget_core:bootstrap_api finished in 201.60000002384186 ms</code></pre></p> <p>有人可以帮助我如何将此小部件添加到我的页面吗?</p> <p>谢谢!</p> </question> <answer tick="false" vote="0"> <p>您可以尝试使用这个包。 <a href="https://www.npmjs.com/package/react-helmet" rel="nofollow noreferrer">https://www.npmjs.com/package/react-helmet</a></p> <pre><code>import React from &#34;react&#34;; import {Helmet} from &#34;react-helmet&#34;; class Application extends React.Component { render () { return ( &lt;div className=&#34;application&#34;&gt; &lt;Helmet&gt; &lt;!-- your script tag here --&gt; &lt;/Helmet&gt; &lt;/div&gt; ); } }; </code></pre> </answer> <answer tick="false" vote="0"> <p>您可以创建一个呈现脚本标签的组件,然后在 jsx 文件中使用它。</p> <p>示例:</p> <pre><code>import React from &#39;react&#39;; const DriftScript = () =&gt; ( &lt;script&gt; &#34;use strict&#34;; !function() { var t = window.driftt = window.drift = window.driftt || []; if (!t.init) { if (t.invoked) return void (window.console &amp;&amp; console.error &amp;&amp; console.error(&#34;Drift snippet included twice.&#34;)); t.invoked = !0, t.methods = [ &#34;identify&#34;, &#34;config&#34;, &#34;track&#34;, &#34;reset&#34;, &#34;debug&#34;, &#34;show&#34;, &#34;ping&#34;, &#34;page&#34;, &#34;hide&#34;, &#34;off&#34;, &#34;on&#34; ], t.factory = function(e) { return function() { var n = Array.prototype.slice.call(arguments); return n.unshift(e), t.push(n), t; }; }, t.methods.forEach(function(e) { t[e] = t.factory(e); }), t.load = function(t) { var e = 3e5, n = Math.ceil(new Date() / e) * e, o = document.createElement(&#34;script&#34;); o.type = &#34;text/javascript&#34;, o.async = !0, o.crossorigin = &#34;anonymous&#34;, o.src = &#34;https://js.driftt.com/include/&#34; + n + &#34;/&#34; + t + &#34;.js&#34;; var i = document.getElementsByTagName(&#34;script&#34;)[0]; i.parentNode.insertBefore(o, i); }; } }(); drift.SNIPPET_VERSION = &#39;0.3.1&#39;; drift.load(&#39;...&#39;); &lt;/script&gt; ); export default DriftScript; </code></pre> <p>然后在你的 jsx 文件中:</p> <pre><code>import React from &#39;react&#39;; import DriftScript from &#39;./DriftScript&#39;; const MyComponent = () =&gt; ( &lt;div&gt; &lt;DriftScript /&gt; &lt;/div&gt; ); export default MyComponent; </code></pre> <p>我希望这有帮助!</p> </answer> <answer tick="false" vote="0"> <p>我按照@nuro007 的回答进行了一些修改,以解决即将出现的问题。</p> <pre><code>&lt;script dangerouslySetInnerHTML={{ __html: ` !function() { var t = window.driftt = window.drift = window.driftt || []; if (!t.init) { if (t.invoked) return void (window.console &amp;&amp; console.error &amp;&amp; console.error(&#34;Drift snippet included twice.&#34;)); t.invoked = !0, t.methods = [ &#34;identify&#34;, &#34;config&#34;, &#34;track&#34;, &#34;reset&#34;, &#34;debug&#34;, &#34;show&#34;, &#34;ping&#34;, &#34;page&#34;, &#34;hide&#34;, &#34;off&#34;, &#34;on&#34; ], t.factory = function(e) { return function() { var n = Array.prototype.slice.call(arguments); return n.unshift(e), t.push(n), t; }; }, t.methods.forEach(function(e) { t[e] = t.factory(e); }), t.load = function(t) { var e = 3e5, n = Math.ceil(new Date() / e) * e, o = document.createElement(&#34;script&#34;); o.type = &#34;text/javascript&#34;, o.async = !0, o.crossorigin = &#34;anonymous&#34;, o.src = &#34;https://js.driftt.com/include/&#34; + n + &#34;/&#34; + t + &#34;.js&#34;; var i = document.getElementsByTagName(&#34;script&#34;)[0]; i.parentNode.insertBefore(o, i); }; } }(); drift.SNIPPET_VERSION = &#39;0.3.1&#39;; drift.load(&#39;...&#39;); ` }} /&gt; </code></pre> </answer> </body></html>

回答 0 投票 0

在我的 Expo 应用程序中,Linking.createURL 在 Google 身份验证后未将应用程序路由到主页

当我在 Expo Go 上测试我的 Expo 应用程序时,经过 Google 身份验证后,它没有将我链接到“home.jsx”页面。这是来自 index.jsx 的代码(作为参考,我使用 Clerk 进行身份验证): 导入 {

回答 1 投票 0

Tailwind 自动完成功能无法在多行(WebStorm)中工作

在 JSX/React 中使用多行字符串作为 className 时,我在 WebStorm 中遇到 Tailwind CSS 自动完成问题。当字符串位于一行上时,自动完成功能可以正常工作,但是当我...

回答 1 投票 0

Astro.js:为每个文件夹创建导航结构

我有一个 Astro 网站,如下所示: 不同部门文件夹foo、bar等 对于每个文件夹,都有一个不同的导航菜单,供内部页面使用。 有一些常见的共享MDX...

回答 1 投票 0

如何在“固定”视口中显示长下拉菜单?

我有一个自定义的日期选择器(对于上下文,其高度为 1050px)。我想将其显示在下拉内容的弹出窗口中。这是我的弹出组件。 我有一个自定义的日期选择器(对于上下文,其高度为 1050px)。我想将其显示在下拉内容的弹出窗口中。这是我的弹出组件。 <div className={styles.popupWrapper} > <div className={styles.popup}> {popupContent comes here} </div> </div> 我总是希望弹出窗口位于页面的中心,所以我使用这样的固定位置。对于所有其他内容,此弹出窗口工作得非常好,但是当将我的日期选择器包装在下拉列表中并希望在弹出窗口中显示它时,选择器超出了视口高度,并且由于固定位置而无法滚动。下面是弹出组件的 css。 .popupWrapper { display: flex; justify-content: center; align-items: center; position: fixed; left: 0; top: 0; width: 100%; height: 100%; z-index: 99; overflow: auto; background-color: rgba(0, 0, 0, 0.3); } .popup { position: relative; display: flex; flex-direction: column; padding: 20px 30px 20px; row-gap: 10px; height: fit-content; background-color: $box-color; border-radius: 12px; z-index: 99; } 我尝试过绝对位置,它允许我滚动,但弹出窗口不一定每次都出现在页面的特定部分,它可以在任何地方,所以顶部%不能设置为固定值,这不是我想如何使用我的弹出组件。 是否有任何解决方法,以便我可以通过滚动页面来显示整个下拉列表? 我看不出固定元素中的下拉菜单会阻止其滚动。 但是,在您的代码中,您已将固定元素内的内容垂直居中。 删除它,元素就可以滚动了。 这是一个使用您提供的代码但“翻译”为纯 HTML 的简单示例。 <body> <div class="popupWrapper"> <div class="popup"> content<br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> content <br> </div> </div> </body> <style> .popupWrapper { display: flex; justify-content: center; /*align-items: center;*/ position: fixed; left: 0; top: 0; width: 100%; height: 100vh; z-index: 99; overflow: auto; background-color: rgba(0, 0, 0, 0.3); } .popup { position: relative; display: flex; flex-direction: column; padding: 20px 30px 20px; row-gap: 10px; height: fit-content; /*background-color: $box-color;*/ border-radius: 12px; z-index: 99; background-image: linear-gradient(red, yellow, blue); } </style> 注意:我不明白为什么您需要在子元素中使用 z-index: 99,但将其保留在其中不会造成任何损害。

回答 1 投票 0

通过命令行 (-r) 运行脚本时 After Effects 崩溃,但在界面上运行良好

我在 After Effects 中运行命令行脚本时遇到了问题,确实需要一些帮助。 这是我正在使用的命令: “C:/Program Files/Adobe/Adobe After Effects 2024/Sup...

回答 1 投票 0

Photoshop 脚本 (JS):复制图层集和子图层

我想通过Photoshop脚本(JS)复制图层集及其所有内容(图层+图层集)。 是否可以完全克隆开箱即用的图层集,或者有人知道吗...

回答 2 投票 0

如何在不干扰其他元素的情况下使徽标居中并保持响应能力?

我正在尝试构建导航栏,需要将徽标在页面上居中,而不破坏其他元素的对齐。布局需要保持响应能力。我如何在确保

回答 1 投票 0

找不到我的应用程序返回 Uncaught TypeError 的原因:无法读取未定义的属性

我使用 useState 来存储从 api 返回的数据: 函数应用程序(){ const [{ ipAddressData, shouldLoadItems }, setModel] = useState({ ip地址数据:[], 应该加载...

回答 2 投票 0

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.