问题描述
我正在尝试创建答题纸,有时也称为“气泡纸”,其中用户单击“ A,B,C或D”,气泡从“亮模式变为暗模式”变为当物理上发生问题时,用铅笔在答案中。 (使用Tailwind.css)
我遇到一个问题:1)仅获得一个更改状态的答案(全部更改),而2)每个问题只能选择一个答案(A,B,C或D)。任何帮助将不胜感激,因为我很近,但是在终点线之前就陷入困境(可以这么说)。
我要从上级组件传入props.start并重复该组件以构建25个增量的答题纸。您不能轻易地传递任何props并用1替换“ props.start”以进行测试。
import React,{ useState } from 'react';
const Bubbles = (props) => {
const [cName,setCname] = useState(
'rounded-full px-2 mx-1 border border-red-600 hover:bg-gray-700 hover:text-white'
);
const handleClick = (event) => {
event.preventDefault();
const answer = event.target.id;
setCname(
'rounded-full px-2 mx-1 border border-red-600 bg-gray-700 text-white'
);
console.log(answer);
};
const NumberedArray = Array.from(Array(25),(_,i) => i + props.start);
return (
<div className='flex flex-wrap flex-col mx-3 overflow-hidden rounded'>
{NumberedArray.map((number,index) => (
<div
className='flex h-10 w-full items-center justify-center bg-gray-100'
key={index}
>
{number}
<div id='A' className={cName} onClick={handleClick}>
A
</div>
<div id='B' className={cName} onClick={handleClick}>
B
</div>
<div id='C' className={cName} onClick={handleClick}>
C
</div>
<div id='D' className={cName} onClick={handleClick}>
D
</div>
</div>
))}
</div>
);
};
export default Bubbles;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
解决方法
您必须实现这一点。
设置默认状态const [visibleOption,setVisible] = useState('')
,const [selctedIndex,setSelctedIndex] = useState('')
,然后在 handleClick 中设置您传递的值,然后根据Condition明智地应用ClassName className = {{${cName} ${visibleOtion === 'A' && visibleClass}
} 。
const [visibleOption,setVisible] = useState('')
const [selctedIndex,setSelctedIndex] = useState('')
const visibleClass = 'rounded-full px-2 mx-1 border border-red-600 bg-gray-700 text-white'
const handleClick = (event,value,index) => {
event.preventDefault();
const answer = event.target.id;
setVisible(value)
setSelctedIndex(index.toString())
console.log(answer);
};
//In return written like this
<div id='A' className={`${cName} ${visibleOtion === 'A' && selctedIndex === index.toString() && visibleClass}`} onClick={(e) => handleClick(e,'A',index)}>
A
</div>
我希望它对您有用。
,将其分为2个单独的组件。 1)ABCD和2)气泡。在ABCD中,映射答案数组。在气泡中,映射出25行答案。这样,您可以在ABCD组件中选择答案,而不会遇到与我相同的问题。