reactjs 相关问题

React是一个用于构建用户界面的JavaScript库。它使用声明范式,旨在既高效又灵活。


我正在研究一个小应用程序,我想知道如何听滚动事件的

window.addEventListener('scroll', () => { (!this.state.showScrollWidget) ? this.setState({showScrollWidget: true}) : null; })

回答 2 投票 0

我用传奇,文字和注释做了一个散点图。但是,当我单击传说文本和与气泡相关的注释时。请检查以下代码。 const getannotati ...

const getAnnotations = () => { if (totalRecords <= 10) { const annotations: any[] = []; const placedPositions: { x: number; y: number }[] = []; const groupedData = new Map<string, { storeLabels: string[], x: number, y: number, z: number }>(); // Group data by total_sales and spearman_correlation data.forEach((item) => { const storeLabel = item[firstColumnFieldName] || "Unknown Store"; const key = `${item.total_sales}-${item.spearman_correlation}`; if (!groupedData.has(key)) { groupedData.set(key, { storeLabels: [], x: item.total_sales, y: item.spearman_correlation, z: item.max_sales }); } groupedData.get(key)!.storeLabels.push(storeLabel); }); // Alternating offsets for y (up and down) let isPositiveYOffset = true; groupedData.forEach(({ storeLabels, x, y, z }) => { // Only include annotations where spearman_correlation is greater than 0.2 or less than -0.2 if (y <= 0.5 && y >= -0.5) return; // Skip if correlation is between -0.2 and 0.2 const combinedLabel = storeLabels.join(", <br>"); // Combine store names with commas const isShortLabel = combinedLabel.length <= 3; // Check if label is short // Calculate bubble size based on total_sales (or another metric if necessary) const bubbleSize = calculateBubbleSize(y, totalRecords, x, z, allLessThanOrEqualZero); // Check if label can fit inside the bubble const labelFitsInsideBubble = !isLabelTooBig(combinedLabel, bubbleSize); // Alternate between positive and negative y offsets for annotation placement const yOffset = isPositiveYOffset ? 30 : -30; // Switch between positive and negative offsets for next annotation isPositiveYOffset = !isPositiveYOffset; // Function to check if an annotation overlaps with either an existing bubble or annotation const isOverlapping = (x: number, y: number, bubbleSize: number) => { // Check if it overlaps with other annotations const annotationOverlap = placedPositions.some(pos => { const distance = calculateDistance(pos.x, pos.y, x, y); return distance < bubbleSize * 0.8; // Adjust threshold as necessary for annotations }); // Check if it overlaps with any bubbles const bubbleOverlap = placedPositions.some(pos => { const distance = calculateDistance(pos.x, pos.y, x, y); return distance < bubbleSize; // Adjust threshold for bubbles }); // If either overlaps, return true return annotationOverlap || bubbleOverlap; }; // Apply the y offset and check for overlap with bubbles and annotations let currentX = x; // Keep the x position same for each annotation let currentY = y + yOffset; // Apply y offset (up/down) // If it overlaps with existing bubbles or annotations, skip this annotation if (isOverlapping(currentX, currentY, bubbleSize)) { return; } // No overlap, so add the position placedPositions.push({ x: currentX, y: currentY }); // Add the annotation to the list annotations.push({ x: x, y: y, text: `<b>${combinedLabel}</b>`, // Display combined label showarrow: !labelFitsInsideBubble, // Show arrow if label is outside arrowhead: 1, arrowwidth: 2, ax: labelFitsInsideBubble ? 10 : 30, // Offset if label is too big ay: labelFitsInsideBubble ? yOffset : -yOffset, // Adjust vertical offset if label is too big font: { size: labelFitsInsideBubble ? 12 : 10, color: labelFitsInsideBubble ? "white" : "black", weight: "800" }, bgcolor: labelFitsInsideBubble ? "transparent" : "white", // Transparent if label fits bordercolor: labelFitsInsideBubble ? "transparent" : "black", borderradius: 10, // Rounded corners xanchor: isShortLabel ? "center" : undefined, yanchor: isShortLabel ? "middle" : undefined, arrowcolor: "black", // Set arrow color }); }); return annotations; } return []; };

回答 1 投票 0


用React和Axios

const technical AnalysisIndicators =({data:initiaLdata,width,ratio})=> { const [data,setData] = usestate(initiaLdata); const [rawdata,setRawdata] = usestate(); const fet ...

回答 1 投票 0


如何使用尾风4.0

tailwind.config.js theme: { extend: { colors: { lightHover: '#fcf4ff', darkHover: '#2a004a', darktheme: '#11001f', }, fontFamily: { Outfit: ["Outfit", "sans-serif"], Ovo: ["Ovo", "serif"] }, boxShadow: { 'black': '4px 4px 0 #000', 'white': '4px 4px 0 #fff', }, gridTemplateColumns: { 'auto': 'repeat(auto-fit, minmax(200px, 1fr))' } }, }, darkMode: 'selector',

回答 1 投票 0


<code>import React from 'react'; import { View, Text, StyleSheet, FlatList, TouchableOpacity, Dimensions, PixelRatio } from 'react-native'; import LeftArrow from "../assets/icons/LeftArrowSvg"; import themes from '../data/themes'; import FastImage from 'react-native-fast-image'; const { width, height } = Dimensions.get('window'); const normalize = (size) => { const scale = Math.min(width / 375, height / 667); const normalizedSize = Math.round(PixelRatio.roundToNearestPixel(size * scale)); return normalizedSize; }; const ThemeListing = ({ navigation }) => { const renderTheme = ({ item }) => { return ( <View style={styles.shadowContainer}> <TouchableOpacity style={styles.themeContainer} onPress={() => navigation.navigate("Theme", {categoryDetails : item})}> <FastImage style={styles.image} source={{ uri: item.categoryImage, priority: FastImage.priority.high }} resizeMode={FastImage.resizeMode.cover} /> <View style={styles.overlay}> <Text allowFontScaling={false} style={styles.categoryText}>{item.categoryName}</Text> </View> </TouchableOpacity> </View> ) } return ( <View style={styles.container}> <View style={styles.header}> <View style={styles.headerInner}> <TouchableOpacity style={styles.backButton} onPress={() => navigation.goBack()}> <LeftArrow width={60} height={40}/> </TouchableOpacity> <Text allowFontScaling={false} style={styles.headerText}>Collections</Text> </View> </View> <FlatList data={themes} renderItem={renderTheme} keyExtractor={(item, i) => String(i)} showsVerticalScrollIndicator={false} scrollEventThrottle={16} decelerationRate={0.99} disableIntervalMomentum={true} contentContainerStyle={{ padding : normalize(10), paddingTop : 0, backgroundColor : "#fff", flexGrow : 1, }} /> </View> ) } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: "#3E434E", }, header: { paddingVertical : normalize(25), width : "100%", justifyContent : "center" }, headerInner: { justifyContent: "flex-start", flexDirection: "row", alignItems: "center", }, backButton: { alignItems : "center" }, headerText: { fontFamily: "Itim-Regular", fontSize: normalize(22), marginTop: normalize(25), color: "#ffffff", }, shadowContainer: { borderRadius: normalize(25), marginVertical: normalize(6), backgroundColor: "#fff", // Needed for shadow to be visible elevation: 8, // Android shadow }, themeContainer: { borderRadius: normalize(25), overflow: 'hidden', position: "relative", }, image: { height: normalize(130), }, overlay: { position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, justifyContent: 'center', alignItems: "center" }, categoryText: { fontFamily: "Itim-Regular", fontSize: normalize(22), color: "#ffffff", } }); export default ThemeListing; </code>

回答 1 投票 0

Micro前端对象无效,因为React子女(typecript)

SO,最近我试图将Micro Frontend实现为我的React Vite Typescript样板作为主机。我使用 @OriginJS/Vite-Plugin-Federation,因为我的项目主要使用Vite运行。我tri ...

回答 1 投票 0


MMSAL,REACT,VITE&REDUX-组件测试无法工作

对于我的寿命,我无法获得简单的组件测试来与此设置(Vite,React,Typescript,Redux-Toolkit和MSAL)一起使用。 任何帮助将不胜感激。 我有一个简单的菜单组合...

回答 0 投票 0


-PRIMEREACT-数据表内线行编辑

Https://www.primefaces.org/primereact/datatable/edit/dit/decon/decontion/primereaeact/primereact/datatable/decont of。按钮我无法做到这一点。我遇到的问题是,当我在自定义组件上捕获点击事件时,我无法在该事件处理程序中获取网格的数据或任何React状态变量,因此无法执行编辑。

回答 1 投票 0

add和执行脚本反应测试-Library和Jest

我们拥有通过查找HTML标签并渲染组件的自定义资产。例如,我们有。 当页面加载脚本时,找到<customABC /> <customABC ...</desc> <question vote="4">我们拥有通过查找HTML标签并渲染组件的自定义资产。例如,我们有<p><code>&lt;script&gt;</code><pre>。 当页面加载脚本时,找到</pre><code>&lt;customABC /&gt;</code><pre>并返回该组件应该是什么。 我正在尝试通过以下内容将脚本添加到我的文档,然后调用渲染。 </pre><code>&lt;customABC /&gt;</code><pre> </pre>debug()仍在显示</p><code> describe(&#39;DisclaimerContainer render tests&#39;, () =&gt; { test(&#39;simple Disclaimer renders disclaimer content&#39;, () =&gt; { const moduleScript = document.createElement(&#39;script&#39;); moduleScript.src = &#34;https://www.example.com/assets/foo/bar/5.7.0/components.js&#34;; moduleScript.type = &#34;module&#34;; moduleScript.async = true; document.body.appendChild(moduleScript); //I&#39;ve also tried document.head.appendChild(moduleScript); const {debug} = render(&lt;ContextDisclaimerContainer history={history}/&gt;); debug(); }); </code><p>,而不是它应该显示的HTML。 </p>当您没有NPM软件包,需要包含自定义脚本时,如何将其配置为在您的React-Testing-library Jest Test中运行? <pre> </pre> 我成功地通过在开玩笑的设置文件中自定义JSDOD来成功加载脚本:<p> <pre><code>&lt;customABC /&gt;</code></pre> </p>关键是用<p><code>// jest.config.js module.exports = { setupFilesAfterEnv: [ &#39;./jest-setup.js&#39;, ], }; // jest-setup.js import { JSDOM } from &#39;jsdom&#39;; const dom = new JSDOM(&lt;!DOCTYPE html&gt;&lt;body&gt;&lt;/body&gt;, { resources: &#39;usable&#39;, runScripts: &#39;dangerously&#39;, }); global.window = dom.window; global.document = dom.window.document; </code></p>配置JSDOM。请参阅</question>ExecutingScriptss<answer tick="false" vote="3">的JSDOM文档。 <p> </p> 您可以在Jest Config(假设JSDOM环境)中设置这些选项:<pre> </pre><code>{ resources: &#39;usable&#39;, runScripts: &#39;dangerously&#39; }</code><p> <pre>请参阅有关配置测试环境的执行脚本</pre>和JEST文档的文档。 <a href="https://github.com/jsdom/jsdom#executing-scripts" rel="nofollow noreferrer"> </a> 我很亲密,但需要两件事才能使它起作用。 </p> 就像其他提到的其他人一样,允许JSDOM执行脚本。 </answer><code> testEnvironment: &#39;jsdom&#39;, testEnvironmentOptions: { resources: &#39;usable&#39;, runScripts: &#39;dangerously&#39;, }, </code><answer tick="false" vote="3"> <p> 我的组件实际上加载了脚本</p>和<pre>我必须等待我的测试可访问预期的更改。 </pre><code>// In &#34;jest.react.config.json&#34; { &#34;testEnvironment&#34;: &#34;jsdom&#34;, &#34;testEnvironmentOptions&#34;: { &#34;resources&#34;: &#34;usable&#34;, &#34;runScripts&#34;: &#34;dangerously&#34; }, } </code><p> <a href="https://github.com/jsdom/jsdom#executing-scripts" rel="nofollow noreferrer"><code>// In your component file const ComponentBeingTested = ({}) =&gt; { ... useEffect(() =&gt; { const script = document.createElement(&#34;script&#34;); script.src = &#34;https://accounts.google.com/gsi/client&#34;; script.onerror = e =&gt; console.log(&#39;error :&gt;&gt; &#39;, e); document.head.appendChild(script); return () =&gt; { document.head.removeChild(script); // Clean up on unmount }; }, []); ... }); </code></a> <a href="https://jestjs.io/docs/configuration#testenvironment-string" rel="nofollow noreferrer"> </a> </p> </answer><answer tick="false" vote="0">

回答 0 投票 0

因此,我正在关注react WebApp https://youtu.be/ldb4uaj87e0?si=8-b0n60emvbllxxd&t=10012 我使用React 19和Tailwind 4.0,因为我仅在08-03-2025安装了此服务器 你...

制作AddJob&deletejob,现在我还添加了Toastify插件时,我注意到当我删除Job时,这将不起作用,并且问题似乎在尝试获取数据。

回答 1 投票 0


有一种方法可以用React-Router v.7?

目标是在用户离开页面之前保存表单。 在我们从v.5切换到React-Router v.7之前,我们使用了历史程序包,该软件包仅与React-Router兼容至V.6。 我们使用的代码...

回答 1 投票 0

TS编译器API:获取JSX组件属性类型

对以下代码进行了处理: 导入类型{reactnode}来自'react' 从“反应”中导入反应 类型props = { 标题:ReactNode } 导出const comp:react.fc=({title})=> { 返回...

回答 1 投票 0


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