首页 > 解决方案 > onClick 事件以使用 Hooks 更改映射数组中的 className

问题描述

我正在尝试创建一个答题卡,有时称为“气泡表”,用户单击“A、B、C 或 D”,气泡从“浅色模式”变为“深色模式”,就像物理发生时一样填写答案。(使用 Tailwind.css)

我遇到了一个问题:1)只获得一个答案来改变状态(它们都改变了),2)每个问题只能选择一个答案(A、B、C、或 D)。任何帮助将不胜感激,因为我很接近但在终点线之前被难住了(可以这么说)。

我从父组件传入 props.start 并重复组件以 25 为增量构建答题纸。您可以轻松地不传递任何道具并将“props.start”替换为 1 来测试这一点。

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>

标签: javascriptarraysreactjsnext.jstailwind-css

解决方案


你必须实现这一点。

设置默认状态const [visibleOption,setVisible] = useState('')const [selctedIndex,setSelctedIndex] = useState('')并且在handleClick中,您必须设置您传递的值,并根据条件应用 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>

我希望它对你有用。


推荐阅读