【问题标题】:How to add class to the current element in map statement如何将类添加到地图语句中的当前元素
【发布时间】:2019-07-16 12:57:11
【问题描述】:

我在 react 中使用了一个类组件,想知道如何将 CSS 类添加到当前,即 map 语句中的单击元素。我想用状态来做。

<div key={q.id} id={q.id}>
    <h2 className={this.state.title}>{q.title}</h2>
    <h3>{q.questionText}</h3>
    <div key={q.id}>
        {q.options.map((opt, index) => (
            <div
                key={opt.id}
                val={opt.val}
                ref={this.options}

                className={index === this.state.clickedItem ? 'myclass' : null}
                onClick={() => this.setState({ clickedItem: index })}>

                <p onClick={this.submitQuestion} ref={this.correctRef}>
                    {opt.text}
                </p>
            </div>
        ))}
</div>

【问题讨论】:

  • 你有没有尝试过?
  • 我几乎尝试了所有我在互联网上可能找到的东西,我花了几天时间在这个上面找到的例子都没有工作。使用 jquery 很容易做到这一点,但我不明白为什么 react 没有一个简单的解决方案。
  • 您对设置这些属性两次的期望是什么? (类名,参考)
  • 您的代码可以根据点击的项目添加自定义类。

标签: reactjs


【解决方案1】:

这里是你的状态

state = {clickedItem: 0}

在渲染中

yourArray.map((el, index) => {
  <div 
  onClick={() => this.setState({clickedItem: index})} 
  key={index} 
  className={index === this.state.clickedItem ? 'Your ClassName' : null}>
   {el.name}
  </div>
})

【讨论】:

  • 为什么你在努力,而OP却不努力。
  • 我试过了,但它似乎不起作用它只是将类添加到数组中的第一个元素
  • @Donald 默认情况下,它只会将类添加到第一个元素,因为state = {clickedItem: 0},当您单击下一个元素时,该项目将获得类。
  • 谢谢,但对我来说,点击时它不会添加到其他项目中
  • 道歉它的工作我在嵌套的 p 标签上有另一个 onclick,当我删除它时它工作了!非常感谢。
【解决方案2】:

使用 useState 钩子功能,没有类。 希望这能有所帮助。

https://codesandbox.io/s/blissful-boyd-6px43?file=/src/App.js

import "./styles.css";
/*
.is-checked {
  background-color: #901c1c;
  color: white;
}
*/


import React, { useState } from "react";

const App = () => {
  const tags = ["portrait", "événements", "voyage", "animaux"];
  const [clickedItem, setClickedItem] = useState(null);

  const handleCSS = (e) => {
    e.preventDefault();
    let selectedTag = e ? parseInt(e.target.id, 10) : null;
    setClickedItem(selectedTag);
    console.log(">> clickedItem", clickedItem);
  };

  return (
    <>
      <div className="App">
        <h1>Hello !</h1>
      </div>

      <div>
        {tags.map((tag, index) => {
          return (
            <button
              type="button"
              key={index}
              onClick={handleCSS}
              id={index}
              className={index === clickedItem ? "is-checked" : null}
            >
              {`#${tag}`}
            </button>
          );
        })}
      </div>
    </>
  );
};

export default App;

【讨论】:

    猜你喜欢
    • 2019-06-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-31
    • 2019-11-17
    • 1970-01-01
    相关资源
    最近更新 更多