我有两个组件,Question.svelte 和 QuestionList.svelte。问题组件有一个清除按钮,可以清除其选项的选择,这些选项是单选按钮。 QuestionList 组件有一个清除按钮,可以清除所有选择。
当我迭代对象并在开始时 console.log 时,它正确地将对象显示为 {id: 1, text: "....", options = [...]}。
当我尝试从 Question 组件记录索引时,它会以“1,”的形式提供 QuestionIndex,而不仅仅是像“1”这样的数字。 我想将循环中的索引传递为“1”而不是“1,”。它会自动添加逗号。
问题列表.svelte
<script>
import Question from './Question.svelte';
export let questions = [
{ id: 1, text: 'What is your favorite color?', options: ['Red', 'Blue', 'Green'], selectedOption: "" },
{ id: 2, text: 'What is your favorite animal?', options: ['Cat', 'Dog', 'Bird'], selectedOption: "" }
];
function handleOptionChange(questionIndex, selectedOption) {
questions[questionIndex].selectedOption = selectedOption;
}
function clearAllSelections() {
questions = questions.map((question) => ({...question, selectedOption: ""}));
console.log('Cleared all selections');
console.log(questions);
}
function clearSingleSelection(e) {
console.log(e);
const questionIndex = e.detail;
console.log(`Cleared Single: ${questionIndex}---`);
console.log(questions);
questions[questionIndex].selectedOption= "";
}
console.log(`QuestionList.svelte`, questions);
</script>
{#each questions as question, index}
<Question
questionId={question.id}
question={question.text}
options={question.options}
selectedOption={question.selectedOption}
questionIndex = {Number(index)},
on:clearSingleSelection={clearSingleSelection}
/>
{/each}
<button on:click={clearAllSelections}>Clear All</button>
问题.svelte
<script>
import { createEventDispatcher } from 'svelte';
export let question, questionId, questionIndex;
export let options = [];
export let selectedOption = '';
const dispatch = createEventDispatcher();
// Function to handle option change
function handleChange(event) {
const selectItem = {
id: questionId,
selectedOption: event.target.value,
}
console.log(`From Question.svelte, changed ${questionIndex}--`);
dispatch('optionChange', selectItem);
}
function handleSingleClear() {
dispatch('clearSingleSelection', questionIndex);
console.log(`From Question.svelte, cleared ${questionIndex}--`);
}
console.log(`Question Index from Question.svelte: ${questionIndex}---`);
</script>
<div class="question-item">
<div class="question-section">
<p>{question}</p>
</div>
<div class="option-section">
{#each options as option}
<input
type="radio"
name={questionId}
value="{option}"
checked={option === selectedOption}
on:change={handleChange}
/>
<label for="{option}">{option}</label>
{/each}
</div>
<button type="button" on:click={handleSingleClear}>Clear</button>
</div>
这里的属性中有一个无关的逗号:
questionIndex = {Number(index)},
应该是:
questionIndex={index}
(已经是数字了。)