【发布时间】:2022-01-11 15:18:18
【问题描述】:
我目前正在做一个 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>
)
}
【问题讨论】:
-
为什么您没有在输入中使用选中的属性?如果您单击两次相同的复选框,您会看到选中/取消选中吗?这些问题有助于我理解问题,谢谢
-
@BruNo 选中属性 - 我通常不使用此复选框属性,我认为这是默认未选中的。如果我两次单击同一个复选框,我确实会看到显示和隐藏的 V 符号。
-
el === ing)} onChange={() => {addIngredientToRecipe(ing )}} id={ing.IngredientId}/> 尝试添加已检查的属性,我认为它应该可以解决您的问题
-
成功了,谢谢!
-
不客气,别忘了在评论加+号,谢谢
标签: jquery reactjs forms checkbox