我目前正在做一個 ReactJS 專案。我有一個表單,應該 console.log 將表單欄位 onSubmit 作為物件。在那種形式中,我有幾個復選框(由 RestAPI 從資料庫中提取并由其他反應組件呈現)。
提交后,復選框未被取消選中。我的問題是,當我手動取消選中它們時,它會將未選中的資料添加到資料物件中。
如何在不手動執行的情況下取消選中提交上的復選框?
這是頁面代碼:
import React, { useState, useEffect } from 'react';
import FCIngredient from '../FunctionalComps/FCIngredient';
import { useNavigate } from 'react-router-dom';
import $ from 'jquery';
const apiUrl = 'https://somelocalhost/'
export default function NewRecipePage() {
const navigate = useNavigate();
const [ingredients, setIngredients] = useState([])
const [recipeIngredients, setRecipeIngredients] = useState([])
const addIngredientToRecipe = (ingredientObject) => {
let tmpIngArr =[...recipeIngredients,ingredientObject];
setRecipeIngredients([...tmpIngArr])
tmpIngArr = [];
}
const Go2Home = () => {
navigate('/');
}
const NewRecipeSubmited = (event) => {
//$(".checkClass").attr("checked", false);//didn't work
const recipeObject = {
Name: event.target.recName.value,
ImageUrl: event.target.recUrl.value,
CoockingMethod: event.target.recMethod.value,
CoockingTime:event.target.recTime.value
}
console.log('recipeObject: ',recipeObject);
console.log('recipeIngredients: ',recipeIngredients);
let cleaningArr = [];
setRecipeIngredients(cleaningArr);
event.preventDefault();
}
useEffect(() => {
fetch(apiUrl, {
method: 'GET',
headers: new Headers({
'Content-Type': 'application/json; charset=UTF-8',
'Accept': 'application/json; charset=UTF-8'
})
})
.then(res => {
return res.json()
})
.then(
(result) => {
setIngredients(result)
console.log(ingredients);
},
(error) => {
});
},[])
return (
<div style={{ color: 'white', width: '100%' }}>
<h1>New Recipe</h1>
<button onClick={Go2Home} >Back Home</button> <br />
<form onSubmit={NewRecipeSubmited}>
<input name="recName" type="text" placeholder='Recipe Name' /><br />
<input name="recMethod" type="text" placeholder='Cooking Method' /><br />
<input name="recTime" type="text" placeholder='Cooking Time' /><br />
<input name="recUrl" type="url" placeholder='Recipe imageURL' /><br />
<p>Please choose the ingredients for your recipe!</p>
<div style={{ display: 'flex' }}>
{ingredients.map((ing) =>
<div>
<input type="checkbox" className='checkClass' onChange={() => {addIngredientToRecipe(ing)}} id={ing.IngredientId}/>
<FCIngredient ingredient={ing} key={ing.IngredientId} /></div>)}
</div>
<button type="submit">Add your new recipe!</button>
</form>
</div>
)
}
uj5u.com熱心網友回復:
是的,代碼幾乎是正確的。以下是所需的更改:
- 您只需
isChecked在每個成分物件中添加一個布爾欄位。 - 在
addIngredientToReceipe()方法中切換所選成分物件的 isChecked 欄位 - 在
NewRecipeSubmitted功能,設定isChecked于false每種成分物件,然后呼叫setIngredients()與修改后的陣列
檢查行內注釋以遵循該方法:
import React, { useState, useEffect } from 'react';
import FCIngredient from '../FunctionalComps/FCIngredient';
import { useNavigate } from 'react-router-dom';
const apiUrl = 'https://somelocalhost/'
export default function NewRecipePage() {
const navigate = useNavigate();
const [ingredients, setIngredients] = useState([])
const [recipeIngredients, setRecipeIngredients] = useState([])
const addIngredientToRecipe = (ingredientObject) => {
let tmpIngArr =[...recipeIngredients,ingredientObject];
setRecipeIngredients([...tmpIngArr])
// 3. Find the ingredient in the array and toggle the checked status
let newIngredients = [...ingredients];
for (let i = 0; i < newIngredients.length; i ) {
if (newIngredients[i].IngredientId === ingredientObject.IngredientId) {
newIngredients[i].isChecked = !newIngredients[i].isChecked;
break;
}
}
// 4. Update ingredients' state
setIngredients(newIngredients);
tmpIngArr = [];
}
const Go2Home = () => {
navigate('/');
}
const NewRecipeSubmited = (event) => {
const recipeObject = {
Name: event.target.recName.value,
ImageUrl: event.target.recUrl.value,
CoockingMethod: event.target.recMethod.value,
CoockingTime:event.target.recTime.value
}
console.log('recipeObject: ',recipeObject);
console.log('recipeIngredients: ',recipeIngredients);
let cleaningArr = [];
setRecipeIngredients(cleaningArr);
// 5. Loop through each ingredients and set the isChecked to false
let newIngredients = [...ingredients];
for (let i = 0; i < newIngredients.length; i ) {
newIngredients[i].isChecked = false;
}
// 6. Update ingredients' state
setIngredients(newIngredients);
event.preventDefault();
}
useEffect(() => {
fetch(apiUrl, {
method: 'GET',
headers: new Headers({
'Content-Type': 'application/json; charset=UTF-8',
'Accept': 'application/json; charset=UTF-8'
})
})
.then(res => {
return res.json()
})
.then(
(result) => {
// 1. Note the new field `isChecked` here
setIngredients(result.map(i => ({...i, isChecked: false})))
console.log(ingredients);
},
(error) => {
});
},[])
return (
<div style={{ color: 'white', width: '100%' }}>
<h1>New Recipe</h1>
<button onClick={Go2Home} >Back Home</button> <br />
<form onSubmit={NewRecipeSubmited}>
<input name="recName" type="text" placeholder='Recipe Name' /><br />
<input name="recMethod" type="text" placeholder='Cooking Method' /><br />
<input name="recTime" type="text" placeholder='Cooking Time' /><br />
<input name="recUrl" type="url" placeholder='Recipe imageURL' /><br />
<p>Please choose the ingredients for your recipe!</p>
<div style={{ display: 'flex' }}>
{ingredients.map((ing) =>
<div>
{/* 2. Note the controlled checkbox here */}
<input type="checkbox" className='checkClass' checked={ing.isChecked} onChange={() => {addIngredientToRecipe(ing)}} id={ing.IngredientId}/>
<FCIngredient ingredient={ing} key={ing.IngredientId} /></div>)}
</div>
<button type="submit">Add your new recipe!</button>
</form>
</div>
)
}
uj5u.com熱心網友回復:
@Borni.Mr 幫助我解決了這個問題:通過為每個復選框提供一個“checked”屬性,jQuery.att.checked 現在正在作業:
原始代碼:
<input type="checkbox" className='checkClass' onChange={() => {addIngredientToRecipe(ing)}} id={ing.IngredientId}/>
固定代碼:
<input type="checkbox" className='checkClass' checked={recipeIngredients.some((el) => el === ing)} onChange={() => {addIngredientToRecipe(ing)}} id={ing.IngredientId}/>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/408866.html
標籤:
