pass-by-const-reference 相关问题


如何在node js中使用DOM更改文本内容

我想做的是 我想在输入错误密码时将标签更改为错误密码 但出现错误 ReferenceError:文档未定义 这是我的 HTML 文件 我想做的是 我想在输入错误密码时将 标签更改为错误密码 但出现错误 ReferenceError:文档未定义 这是我的 HTML 文件 <form action="/check" method="POST"> <label for="password">Password:</label> <input type="text" id="password" name="password" required> <input type="submit" value="Submit"> <p></p> </form> 这是我的 javascript 文件内容 import express from "express"; import {dirname} from "path"; import { fileURLToPath } from "url"; import bodyParser from "body-parser"; const __dirname = dirname(fileURLToPath(import.meta.url)); const app = express(); const port = 3000; const pass = "ILoveProgramming"; var enter = ""; app.use(bodyParser.urlencoded({extended:true})); function checker(req, res, next){ enter = req.body.password; console.log(enter); next(); } app.use(checker); app.get("/", (req,res) =>{ res.sendFile(__dirname +"/public/index.html"); }); app.post("/check",(req,res)=>{ if(pass === enter){ res.sendFile(__dirname+"/public/secret.html"); } else{ document.querySelector("p").textContent("The paswrd is wrong"); console.log("The password is incorrect"); } // console.log(enter); }); app.use(bodyParser); app.listen(port, () =>{ console.log(`server is live at ${port}`); }); 我对这一切都是新手所以把我当作一个没有任何经验的人 document对象是浏览器DOM API的一部分,它在服务器端不可用。在浏览器控制台上,它是 window 对象的属性。 window.document。 您正在尝试操作服务器上的 DOM,这是不可能的。您应该在浏览器接收并呈现 HTML 页面后在客户端处理 DOM 操作。为此,您应该在 HTML 文件内有一个 script 标签。 <script> // inside here you add your logic to access document <script/> script标签将在浏览器上执行,您可以访问此标签内的document对象


将 props 传递给 nextjs 中的页面组件

我正在使用 nextjs 的 withlayout 函数为某些页面添加侧边栏。 导出类型 PageWithLayout = NextPage & { withLayout?:(页面:ReactElement)=> 我正在使用 nextjs 的 withlayout 函数为某些页面添加侧边栏。 export type PageWithLayout<P = {}, IP = P> = NextPage<P, IP> & { withLayout?: (page: ReactElement) => ReactNode; }; 这是我的使用方法: export const Interactions: PageWithLayout = () => { const [ getInteractions, { data: interactionData, fetchMore, variables, loading: isInteractionsLoading, error: isInteractionsError, }, ] = useGetInteractionsLazyQuery({ notifyOnNetworkStatusChange: true, fetchPolicy: "network-only", ssr: false, }); return ( <> <Box height={"100vh"}> </Box> </> ); }; Interactions.withLayout = (page: ReactElement) => { // how do I pass isInteractionsLoading as a prop to this component return <Layout>{page}</Layout>; }; export default Interactions; 我想要实现的是将 isInteractionsLoaded 和 isInteractionsError 作为属性传递给我的布局组件,以便我可以渲染这些状态。有没有一种方法可以实现此目的,而无需将布局组件移动到页面组件内? 创建一个包装组件的 React Context 提供程序可能是您使用的解决方案,如果您不想使用任何其他包或不想使用 redux 等更强大的工具,则可以使用。 但是在这里使用有点尴尬,具体取决于包含交互的组件树是什么样子。否则可以根据您的需要使用 _app 入口点。 示例上下文和用法 import React from 'react'; export const InteractionContext = React.createContext({ isInteractionsLoading: false, isInteractionsError: null, }); // parent component or _app if necessary const ProviderComponent = () => { return ( <InteractionContext.Provider value={{ isInteractionsLoading, isInteractionsError }}> <Interactions /> </InteractionContext.Provider> ); }; const Layout = ({ children }) => { const { isInteractionsLoading, isInteractionsError } = useContext(InteractionContext); // Now you can use isInteractionsLoading and isInteractionsError here // ... return <div>{children}</div>; };


创建名为“springSecurityFilterChain”的 bean 时出错

我一直在关注Spring Security Reference,我只添加了这些类: @配置 @EnableWebMvcSecurity 公共类 WebSecurityConfig 扩展 WebSecurityConfigurerAdapter { @


imap_open 在服务器 Aruba.it 上

为了接收邮件,我通常使用: imap_open('{mail.sito.com:143/notls}', $user, $pass); 然而,当我必须连接到 Aruba 服务器上的电子邮件时,我遇到了困难。 我尝试过: {mail.website.c...


Python 多处理 - 如何将 kwargs 传递给函数?

如何使用 Python 的多重处理将字典传递给函数?文档:https://docs.python.org/3.4/library/multiprocessing.html#reference 说要传递字典,但我保留了...


Firestore 触发器 Python 云函数(第 2 代)- 采用 1 个位置参数,但已给出 2 个

我已按照示例部署了 firestore 触发器函数 on_document_created:https://firebase.google.com/docs/reference/functions/2nd-gen/python/firebase_functions.firestore_fn#functions @


我做错了什么? (编码语法错误)

为什么我的 fieldName 和 order 上会出现红线?我在这里参考 API 参考: https://www.wix.com/velo/reference/wix-pricing-plans-backend/orders/listcurrentmemberorders 这是来自...的示例


询问正确的SQL查询

const personid = result.map(item => item.person_id) console.log("personen", personid) const formattedid = personid.join(","); const nameResult = 等待


ReferenceError:找不到变量:require

我在将node_modules加载到我的网页之一时遇到问题。我安装了 npm(node.js),并且想使用 require() 函数在我的网站上初始化 Firebase,但我不知道为什么,但它抛出了 Reference ...


Javascript 函数 openFullscreen() ,如何让它在页面上的多个 iframe 上工作

在页面上我有一个 iframe,src 中有 *.pdf 文件。 <p>在页面上我有一个 iframe,src 中有 *.pdf 文件。</p> <pre><code>&lt;div class=&#34;node--view-mode-full&#34;&gt; &lt;p&gt;&lt;iframe allow=&#34;fullscreen&#34; allowfullscreen=&#34;&#34; frameborder=&#34;0&#34; height=&#34;980&#34; scrolling=&#34;no&#34; src=&#34;https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf&#34; width=&#34;660&#34;&gt;&lt;/iframe&gt;&lt;/p&gt; &lt;p&gt;&lt;iframe allow=&#34;fullscreen&#34; allowfullscreen=&#34;&#34; frameborder=&#34;0&#34; height=&#34;980&#34; scrolling=&#34;no&#34; src=&#34;https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf&#34; width=&#34;660&#34;&gt;&lt;/iframe&gt;&lt;/p&gt; &lt;/div&gt; </code></pre> <p>浏览器中内置的 pdf 查看器现在不支持 iframe 中的全屏模式。</p> <p>我找到了解决方案<a href="https://www.w3schools.com/howto/howto_js_fullscreen.asp" rel="nofollow noreferrer">https://www.w3schools.com/howto/howto_js_fullscreen.asp</a>,解决了问题 - 以全屏模式打开 iframe。在 w3schools 的示例中,打开 iframe 的按钮已存在于 HTML <a href="https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_fullscreen" rel="nofollow noreferrer">https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_fullscreen</a>.</p> <p>在我的解决方案中,我通过 javascript 添加按钮,因为带有 iframe 的页面已经存在,但没有此类按钮:</p> <pre><code>jQuery(document).ready(function($){ $(&#34;.node--view-mode-full iframe[src*=&#39;.pdf&#39;]&#34;).each(function (index) { $(this).addClass(&#39;fullscreenframe&#39;); $(this).attr(&#39;id&#39;, &#39;fullscreen-&#39;+index); $(&#39;&lt;button onclick=&#34;openFullscreen()&#34;&gt;Open in Fullscreen Mode&lt;/button&gt;&amp;nbsp;&lt;strong&gt;Tip:&lt;/strong&gt; Press the &#34;Esc&#34; key to exit full screen.&lt;br&gt;&#39;).insertBefore(this); }); }); </code></pre> <p>然后添加一个全屏打开 iframe 的功能(与 w3schools 相同):</p> <pre><code>function openFullscreen() { var elem = document.getElementsByClassName(&#34;fullscreenframe&#34;)[0]; if (elem.requestFullscreen) { elem.requestFullscreen(); } else if (elem.webkitRequestFullscreen) { /* Safari */ elem.webkitRequestFullscreen(); } else if (elem.msRequestFullscreen) { /* IE11 */ elem.msRequestFullscreen(); } }; </code></pre> <p>当页面上只有一个带有 *.pdf 的 iframe 时,Everysing 工作正常。但是,当我在页面上有两个或多个 iframe,并且单击任何 iframe 附近的“以全屏模式打开”任何按钮时,我总是在全屏模式下只看到第一个 *.pdf...</p> <p>我知道,这是因为我只得到 elem = document.getElementsByClassName("fullscreenframe")[0]; 中的第一个 iframe;</p> <p>我知道我需要使用类似的每个或类似的东西,但我无法解决它。在搜索关于页面上一个全屏元素的所有解决方案时,没有关于页面上多个元素的解决方案...谢谢。</p> </question> <answer tick="true" vote="0"> <p>也许是这样的:</p> <pre><code>jQuery(document).ready(function($){ $(&#34;.node--view-mode-full iframe[src*=&#39;.pdf&#39;]&#34;).each(function (index) { $(this).addClass(&#39;fullscreenframe&#39;); $(this).attr(&#39;id&#39;, &#39;fullscreen-&#39;+index); $(&#39;&lt;button onclick=&#34;openFullscreen(&#39; + index + &#39;)&#34;&gt;Open in Fullscreen Mode&lt;/button&gt;&amp;nbsp;&lt;strong&gt;Tip:&lt;/strong&gt; Press the &#34;Esc&#34; key to exit full screen.&lt;br&gt;&#39;).insertBefore(this); }); }); function openFullscreen(index) { var elem = document.getElementsByClassName(&#34;fullscreenframe&#34;)[index]; if (elem.requestFullscreen) { elem.requestFullscreen(); } else if (elem.webkitRequestFullscreen) { /* Safari */ elem.webkitRequestFullscreen(); } else if (elem.msRequestFullscreen) { /* IE11 */ elem.msRequestFullscreen(); } } </code></pre> </answer> <answer tick="false" vote="0"> <p>为什么不整合 jQuery?</p> <pre><code>const fullScreen = element =&gt; element.requestFullScreen(); // all modern browsers $(function(){ $(&#34;.node--view-mode-full iframe[src*=&#39;.pdf&#39;]&#34;).each(function (index) { $(this).addClass(&#39;fullscreenframe&#39;); $(this).attr(&#39;id&#39;, &#39;fullscreen-&#39;+index); $(&#39;&lt;button class=&#34;fullScreen&#34;&gt;Open in Fullscreen Mode&lt;/button&gt;&amp;nbsp;&lt;strong&gt;Tip:&lt;/strong&gt; Press the &#34;Esc&#34; key to exit full screen.&lt;br&gt;&#39;).insertBefore(this); }); $(&#34;.fullScreen&#34;).on(&#34;click&#34;, function() { const $iFrame = $(this).closest(&#39;p&#39;).find(&#39;iframe.fullscreenframe&#39;); if ($iFrame) fullScreen($iFrame.get(0)); // pass the DOM element }); }); </code></pre> </answer> </body></html>


为什么const指针可以指向非常量对象?

//示例1 常量双饼 = 3.14; // 常量对象 const double *cptr = &pie; // 指向 const 对象的指针 双 *ptr = &pie; // 错误 - 指向 const 的非 const 指针 //


Flutter Hive 更新

返回ListTile( tileColor:组件颜色, 前导:图标按钮( 图标:widget.isDone? const Icon(Icons.check_box) : const Icon(Icons.check_box_outline_blank), 颜色:


自定义骑行存在(discord.js v14)

const 猫鼬 = require("猫鼬") 需要(“dotenv”).config() const {Client,ActivityType} = require("discord.js") 模块. 导出 = { 名称:'准备好', /** ...


scryRenderedComponentsWithType 返回一个空数组

我对 React 应用程序进行了以下测试: it('有 7 个 NavBarItems', () => { const 组件 = ReactTestUtils.renderIntoDocument(); const navBarItems = ReactTestUtils.


我可以有一个同时接受 const-ref 和非 const-ref 指针的 C++ 方法吗?

我有一些辅助方法,它们通过引用接受指针,如果满足某些条件,则将其向前推进。这是一个例子: char32_t readCodePoint(const char8_t *¤t, const char...


类模板针对 const 和非 const 指针的部分特化

我正在尝试制作一个具有指针类型的非类型模板参数的类模板,它有 const 和非 const 指针的两个特化。 这是我最好的尝试,被 Clang 接受并......


如何将 const 添加到指向类型?

假设我有一个类模板: 模板 结构A { T值; 无效 foo(自动乐趣) { 乐趣(价值); // ^^^^^^^ 将值作为 const 对象传递 } }; 我想将 const 添加到 v...


{;} 和 (,) 有什么区别? [重复]

在 React.js 中,将函数或常量编写为 const aHandler = () => {function1() ;函数2();} 与 const aHandler = () => (函数 1() , 函数 2()) 从...


我正在尝试使用 Fluent-ffmpeg 合并视频,但有时它会合并视频,但每当我们第二次尝试合并视频时,它都会显示错误

const express =require('express') 常量应用程序 = Express() const ffmpeg = require('流畅的 ffmpeg') const ffmpegPath = require('@ffmpeg-installer/ffmpeg') const ffprobe = require('@ffprobe-installer/ff...


Discord.js 聊天机器人

请帮助我。这是我下面关于discord.js 聊天机器人的代码 const fetch = require("node-fetch"); const {ChannelType} = require("discord.js"); client.on('messageCreate...


Node Express.js 应用程序在本地运行良好,但在 Docker 中显示“无法获取/”

我在 Node 应用程序中定义了一个 Express.js 服务器,如下所示: const express = require('express') const SignRequest = require('./SignRequest/lambda/index.js') const VerifyResponse = require('./


浏览器未实现Geolocation.requestPermissions,并且错误始终未被捕获?

从“@capacitor/geolocation”导入{地理位置}; const request_perm = () => { 尝试 { const stuff = Geolocation.requestPermissions(); console.log(东西,“东西&


整数转换为指针是什么意思?

给出以下代码: 令 mut a = 5; 设 b = &mut a; *b = 6; println!("{:p}",&a as *const i32 ); println!("{:p}",a as *const i32 ); println!("{:p}",&a); 原则...


Chai returnedWith 未正确链接

我已经阅读了大量的帖子和文档,但似乎无法弄清楚为什么这段代码不能像我认为的那样工作。 const chai = require('chai'); const 期望 = chai.expect; const chaiAsPromised = r...


函数后面的const如何优化程序? [重复]

我见过一些这样的方法: void SomeClass::someMethod() const; 这个 const 声明有什么作用,它如何帮助优化程序? 编辑 我看到这个问题的第一部分...


如何创建松果客户端,它给出错误

存在于松果.ts 中 从 '@pinecone-database/pinecone' 导入 { PineconeClient } 导出 const getPineconeClient = async () => { const client = new PineconeClient() 等待客户。


使用 vanilla-extract 和 esbuild 导入图像

我在使用 vanilla-extract 和 esbuild 导入图像时遇到问题 我的构建文件: const { build } = require("esbuild"); const { vanillaExtractPlugin } = require("@vanilla-extract/


类型错误:无法读取 <img/> 标记中未定义的属性(读取“0”)

从“react”导入React; const DataPage = ({ 数据 }) => { const dataList = 数据; 控制台.log(数据列表); 返回 (


文件大小错误节点js

从大文件下载 25mb 小块时,这些块实际上比 25mb 大得多。有人可以帮忙吗? const fs = require('fs') const 文件 = fs.readdirSync('../in/') 文件.map(


React Js - {;} 和 (,) 有什么区别? [重复]

这可能是一个非常菜鸟的问题。但是在 ReactJs 中,将函数或常量编写为 const aHandler = () => { 函数 1 ;函数2;} 与 const aHandler = () => (


这里是否误报:警告C4172:返回局部变量或临时变量的地址?

在以下代码中: #包括 #包括 模板 类索引{ 民众: const std::string& 文本; const std::向量&...


是否使用 useState 来反应原生动画 => new Animated.Value() ?

在react-native中使用Animated.Value()的最佳方法是什么? 是否使用 useState() ? const [fadeAnim] = useState(new Animated.Value(0)) 或者 const fadeAnim = new Animated.Value(0) React-nati...


在 onCompleted 执行之前加载状态更新会导致内容闪烁

我目前的 React 组件中有这个突变: 从 '@remix-run/react' 导入 { useNavigate } ... const MyComponent = () => { const { 重定向到 } = useNavigate(); ... 常量 [


如何解决加载响应数据失败:未找到具有给定标识符的资源的数据

发布API 导出 const resendInvitation = async (userName) => { wait API.post( 'delta-api',user-mgmt/users/${userName}/resendInvitation, {} ); }; const handleResendInvitation = async () =>...


MUI-table:mui 表组件中交替行的不同颜色不起作用

为备用表格行添加不同的颜色不起作用 函数行(道具){ const { 行 } = 道具; const StyledTableRow = styled(TableRow)(({ 主题 }) => ({ '&:第 n 个类型...


为什么没有从指针到引用的隐式转换到const指针[重复]

我将用代码来说明我的问题: #包括 void PrintInt(const unsigned char*& ptr) { 整数数据=0; ::memcpy(&data, ptr, sizeof(data)); // 推进 po...


C++ 中的“const class <class_name>&”是什么?

我在Ardupilot代码中偶然发现了这个成员函数声明: void update(const class Aircraft &aircraft) override; 您可以在他们的代码库中随处看到它:链接 什么是


未捕获的类型错误:Promise.reject 不是构造函数[已关闭]

我遇到了问题; const p4 = new Promise.reject("错误"); 或者 const p4 = new Promise.resolve("成功"); 我在定义时遇到这样的错误; 未捕获的类型错误:Promise.reject ...


如何从 const boost::multi_array 获取特定元素

我想知道如何从 const boost::multi_array 对象中读取元素。 事实上,据我所知,我不能使用运算符 [],因为它也用于赋值。 我有一个 3D 维度...


如何控制列表元素抛出键盘事件

https://stackblitz.com/edit/react-o1ra7c 用户搜索结果后,用户尝试使用键盘事件箭头需要向下移动。 https://stackblitz.com/edit/react-o1ra7c 用户搜索结果后,用户尝试使用键盘事件箭头需要向下移动。 <div> <input onChange={handleSearchChange}/> <div css={countryDataCss}> {countryList?.map((country) => ( <div key={country.countryCode}> <span css={countryCss}>{country.countryName}</span> <span css={countryDialCodeCss}> {country.countryDialNo} </span> </div> ))} </div> </div> 您可以使用 javascirpt 事件 onkeydown,对于 React 来说是 onKeyDown,它提供了所需的行为,请检查下面的 stackblitz! import React from 'react'; import './style.css'; import { useState } from 'react'; export default function App() { const [searchText, setSearchText] = useState(''); const [selectedCountry, setSelectedCountry] = useState('SG'); const [activeIndex, setActiveIndex] = useState(0); const [selectedDialCode, setSelectedDialCode] = useState('+65'); const countryCodeListResponse = [ { countryCode: 'IND', countryDialNo: '+91', countryName: 'India' }, { countryCode: 'SG', countryDialNo: '+65', countryName: 'Singpare' }, ]; const [countryList, setCountryList] = useState(countryCodeListResponse); function handleSearchChange(e) { const searchText = e.target.value.toLowerCase(); if (countryCodeListResponse) { const updatedList = countryCodeListResponse .filter((el) => el.countryName.toLowerCase().includes(searchText)) .sort( (a, b) => a.countryName.toLowerCase().indexOf(searchText) - b.countryName.toLowerCase().indexOf(searchText) ); setSearchText(searchText); setCountryList(updatedList); } } const onSelectCountry = (code, dialCode) => { setSelectedCountry(code); setSelectedDialCode(dialCode); setSearchText(''); setCountryList(countryCodeListResponse); }; const onKeyDown = (event) => { console.log(event); switch (event.keyCode) { case 38: // arrow up if (activeIndex > 0 && activeIndex <= countryList.length - 1) { setActiveIndex((prev) => prev - 1); } break; case 40: // arrow down if (activeIndex >= 0 && activeIndex < countryList.length - 1) { setActiveIndex((prev) => prev + 1); } break; case 13: const country = countryList[activeIndex]; onSelectCountry(country.countryCode, country.countryDialNo); break; default: break; } }; return ( <div class="dropdown"> <div class="search"> <div> <span>{selectedCountry}</span> <span>{selectedDialCode}</span> </div> <input class="search-input" onKeyDown={(e) => onKeyDown(e)} placeholder="Search" value={searchText} onChange={handleSearchChange} /> </div> <div class="list"> {countryList?.map((country, index) => ( <div onKeyDown={(e) => onKeyDown(e)} className={index === activeIndex ? 'active' : ''} tabIndex="0" key={country.countryCode} onClick={() => onSelectCountry(country.countryCode, country.countryDialNo) } > <span>{country.countryName}</span> <span>{country.countryDialNo}</span> </div> ))} </div> </div> ); } 堆栈闪电战


“const int*”类型的值不能用于初始化“int* const”类型的实体

我在 vs 2022 社区版本上有 c++ 代码。 导入标准; int main() { constexpr int x = 10; constexpr int* p = &x; } 我不允许将 x 的地址分配给 p


如何在 RegExp javascript 中排除搜索词中的逗号

我有字符串: const text = 'A Jack# Jack#aNyWord Jack,Jack'; 我只想搜索单词“Jack”,但如果 Jack 包含 # 字符,则表示真正的均值匹配。 我尝试像: const text = 'A Jack#...


react-hook-form useForm 每次在 Nextjs 页面路由上执行

嗨,我是 Nextjs(v14) 的新手。我想使用react-hook-form 实现多页面表单。 然而,似乎每次都会执行useForm,并且defaultValues是在页面路由中设置的(点击 嗨,我是 Nextjs(v14) 的新手。我想使用react-hook-form 实现多页面表单。 不过,好像每次都会执行useForm,并且在页面路由时设置defaultValues(点击<Link to=XX>)。 如何跨多个页面保存表单数据? 请帮助我。 这是我的代码。 _app.tsx return ( <div> <FormProvider> <Component {...pageProps} /> </FormProvider> </div> ); FormProvider.tsx export const FormProvider = ({ children, }: { children: React.ReactNode; }) => { const defaultValues: MyForm = { name: '', description: '' }; const form = useForm({ defaultValues, resolver: zodResolver(MyFormSchema), }); const onSubmit = () => console.log("something to do"); return ( <Form {...form}> <form onSubmit={form.handleSubmit(onSubmit)}>{children}</form> </Form> ); }; 您正在寻找的是跨多个页面维护的某种全局状态。对于这个例子,我将使用 React 的上下文 API,如果这不适合您的用例,您可以找到一些其他状态管理库。 首先,您需要创建一个全局上下文,并在表单提供程序中包含一个全局状态 // FormProvider.tsx import { createContext, useContext, useState } from 'react'; const FormContext = createContext(); // Exported to be used in other components export const useFormContext = () => useContext(FormContext); export const FormProvider = ({ children }) => { const [formData, setFormData] = useState({}); return ( <FormContext.Provider value={{ formData, setFormData }}> {children} </FormContext.Provider> ); }; 现在您需要用 FormProvider 包装您的应用程序 // You are already doing this part //_app.tsx return ( <div> <FormProvider> <Component {...pageProps} /> </FormProvider> </div> ) 现在你可以像这样使用它了。请记住,您将更新表单的全局状态,该状态将在您的所有页面上发生变化。 // In your form component import { useForm } from 'react-hook-form'; import { useFormContext } from '../path/to/formContext'; const MyFormComponent = () => { const { formData, setFormData } = useFormContext(); const { register, handleSubmit } = useForm({ defaultValues: formData, resolver: zodResolver(MyFormSchema), }); const onSubmit = (data) => { setFormData(data); // Handle form submission }; return ( <form onSubmit={handleSubmit(onSubmit)}> {/* Form fields */} </form> ); }; 您可以从其他页面访问数据的示例 // In another page or component import { useFormContext } from '../path/to/formContext'; const AnotherPage = () => { const { formData } = useFormContext(); // Use formData as needed };


在React中不显示服务器上的图像

这是代码 从“反应”导入反应; 从“react-dom/client”导入ReactDOM; const 标头 = () => { 返回 ( <... 这是代码 import React from "react"; import ReactDOM from "react-dom/client"; const Header = () => { return ( <div className="header"> <div className="logo-container"> <img className="logo" src="/assets/logo.jpg" /> </div> <div className="nav-items"> <ul> <li>Home</li> <li>About us</li> <li>Contact us</li> <li>Cart</li> </ul> </div> </div> ); }; const AppLayout = () => { return ( <div className="App"> <Header /> </div> ); }; const root = ReactDOM.createRoot(document.getElementById("root")); root.render(<AppLayout />); 请帮助我,因为我是新反应。 我期待在服务器上显示图像 如果仍然不起作用,请尝试在上面的代码中添加 alt 标签 试试这个: 从“react”导入React; 从“react-dom/client”导入 ReactDOM; const Header = () => { return ( <div className="header"> <div className="logo-container"> <img className="logo" src={process.env.PUBLIC_URL + "/assets/logo.jpg"} alt="Logo" /> </div> <div className="nav-items"> <ul> <li>Home</li> <li>About us</li> <li>Contact us</li> <li>Cart</li> </ul> </div> </div> ); }; const AppLayout = () => { return ( <div className="App"> <Header /> </div> ); }; const root = ReactDOM.createRoot(document.getElementById("root")); root.render(<AppLayout />);


我需要用非常量元素锁定 const 容器吗?

我开发了一个多线程应用程序(用 C++ 开发),它具有各种集合,其中容器(向量、映射等)在初始化时是 const,但容器中的元素...


如何在添加间隔的同时在获取请求中使用超时来停止轮询

我正在轮询我的报告,并在每个请求之间添加 5 秒的间隔。 const addDelay = 超时 => 新 Promise(resolve => setTimeout(resolve, timeout)) 导出 const myReport = () => a...


在使用 TypeScript 进行 React 时,输入字段在“值”处给出错误

从“react”导入{SetStateAction,useState} const 登录表单 =() =>{ const [名称,setName] = useState(); const [全名,setFullname] = useState import { SetStateAction, useState } from "react" const Loginform =() =>{ const [name, setName] = useState<String | null>(); const [fullname, setFullname] = useState<String | null>(); const inputEvent =(event: { target: { value: SetStateAction< String |null | undefined >; }; })=>{ setName(event.target.value) } const Submit = ()=>{ setFullname(name) } return <> <h1>Enter Your Name </h1> <input type="text" placeholder="Enter your name" onChange={inputEvent} value={name}/> <button onClick={Submit}>Submit</button> <h1>Hi {fullname==null? "Guest" :fullname}</h1> </> } export default Loginform <input type="text" placeholder="Enter your name" onChange={inputEvent} value={name}/> 上一行中的“value”属性显示错误 这是错误详细信息: (property) React.InputHTMLAttributes<HTMLInputElement>.value?: string | number | readonly string[] | undefined Type 'String | null | undefined' is not assignable to type 'string | number | readonly string[] | undefined'. Type 'null' is not assignable to type 'string | number | readonly string[] | undefined'.ts(2322) index.d.ts(2398, 9): The expected type comes from property 'value' which is declared here on type 'DetailedHTMLProps<InputHTMLAttributes<HTMLInputElement>, HTMLInputElement>' 也尝试写 return as any。或者尝试添加 string[],但出现错误。 进行以下调整: 将 String 替换为 string,因为原始 Typescript 类型是小写的 (number, string, boolean, etc) TypeScript 报告此错误,因为属性值不接受 null 作为值,而是接受 undefined。将代码更新为: const [name, setName] = useState<string>() 这会使用 string 作为默认类型来初始化状态。 初始状态隐式地被视为 undefined,因为如果未显式提供,TypeScript 会将类型的默认值设置为 undefined。 为了简单起见,您不需要解构事件。使用内联函数,如下例所示: <input type="text" placeholder="Enter your name" onChange={(e) => setName(e.target.value)} value={name}/> 我使用你的代码创建了一个 CodeSanbox,它似乎只需要很少的修改就可以正常工作。 您可以在这里找到沙盒 这是我想出的代码 import { SetStateAction, useState } from "react"; const Loginform = () => { const [name, setName] = useState<string | null>(); const [fullname, setFullname] = useState<string | null>(); const inputEvent = (event: { target: { value: SetStateAction<string | null | undefined> }; }) => { setName(event.target.value); }; const Submit = () => { setFullname(name); }; return ( <div> <h1>Enter Your Name </h1> <input type="text" placeholder="Enter your name" onChange={inputEvent} value={name} /> <button onClick={Submit}>Submit</button> <h1>Hi {fullname == null ? "Guest" : fullname}</h1> </div> ); }; export default Loginform;


React 中 fetch 调用后的清理函数

const[imageContainer,setImageContainer] = useState([]) 常量导航 = useNavigate(); 使用效果(()=>{ Promise.all([ fetch("https://www.themealdb.com/api/json/v1/1/


React,useCallback更新了一个状态变量,该变量也存在于其依赖数组中,它如何防止无限重新渲染?

考虑以下代码 从 'react' 导入 { useMemo, useState, useCallback } 函数应用程序(){ const [count, setCount] = useState(0); const handleClick = useCallback(() => { 设置公司...


const 泛型和 `typenum` 箱子有重叠的目的吗?

在了解了 const 泛型并偶然发现了 typenum 箱子之后,我对它们似乎有重叠的目的这一事实感到困惑 - 使用数值作为类型。 唯一不同的是...


© www.soinside.com 2019 - 2024. All rights reserved.