javascript - 从 Store 检索值时返回不正确的值
问题描述
我有一个显示一组按钮的组件:
对于按钮中的每次单击,我都想显示不同的视图并将当前视图设置为“步骤”变量。由于我不想从应用程序中的不同组件访问此变量,因此我将此“步骤”变量存储在商店中。
我正在从渲染列表时设置的数据属性中检索值:
StepNavigator.svelte
<script>
import { step } from "../stores/step.js";
import { onMount } from "svelte";
import Icon from "./Icon.svelte";
function setStep(e) {
step.update(n => e.target.tabIndex);
}
let stepItems = [
{
title: "Option 1",
selections: []
},
{
title: "Option 2",
selections: ["One selection"]
},
{
title: "Option 3",
selections: []
},
{
title: "Option 4",
selections: ["Selection 1", "Selection 2"]
},
{
title: "Option 5",
selections: []
},
{
title: "Option 6",
selections: []
}
];
</script>
<section class="step-navigator">
<h2>Configure product item 1</h2>
<p>Lorem ispum dolor samet dolor ipsum lorem samet.</p>
<ul>
{#each stepItems as stepItem, index}
<li>
<button class={$step === index ? 'active' : 'inactive'} on:click={setStep} tabindex={index}>
<div>
<h3>{stepItem.title}</h3>
<div class="selected-items">
{#if stepItem.selections.length > 0}
{#each stepItem.selections as selection, index}
{#if index !== 0}, {selection}{:else}{selection}{/if}
{/each}
{:else}Nothing selected{/if}
</div>
</div>
<Icon iconType="ok" iconColor={stepItem.selections.length > 0 ? 'var(--theme-color--success)' : '#999'} strokeWidth="4" />
</button>
</li>
{/each}
</ul>
<div class="price-container">
<div class="price">7560 USD</div>
<div class="price-information">Disclaimer text goes here</div>
</div>
</section>
Step.js
import { writable } from 'svelte/store';
export const step = writable(0);
问题是我在单击按钮时随机获得值“-1”:
为什么会这样?我在这里做错了什么?
解决方案
我同意您的标签索引返回为 很奇怪-1
,即使您似乎正确设置了它们。
但是我可能不使用tabIndex
in setStep
,而是直接传递索引,如下所示:
function setStep(index) {
step.update(n => index);
}
<button class={$step === index ? 'active' : 'inactive'} on:click={() => setStep(index)} tabindex={index}>
这是一个 Svelte REPL:https ://svelte.dev/repl/b70ed5be24074cf48c3d3e6a375c327e?version=3.12.1
旁注,但如果您不使用该n
变量,那么使用它可能会稍微干净一些,set
而不是update
:
function setStep(index) {
step.set(index);
}
推荐阅读
- google-api - 使用 Google 的 API 将字符串拆分为单词?
- swift - MapKit 本地搜索结果填充表格
- node.js - 无法关闭 Nodemon SIGINT 事件处理程序内的猫鼬连接
- java - 在android中添加带有图标和名称的mikepenz materialdrawer布局
- java - 如何将消息拆分为更多消息
- javascript - 如何设置 heroku 环境变量出现在 NextJS 应用程序中?
- c# - C#最短的方法是什么
- node.js - 节点 JS 图像二进制字符串
- android - ios 和 Android 上 React Native 中的首字下沉
- maxscript - 在 Maxscript 中按下焦点按钮