在React-Js中选择和取消选择多个DIV

发布于 2025-02-06 21:07:26 字数 449 浏览 1 评论 0 原文

在react-js单击一个Div中,DIV将突出显示并再次单击它将正常,我们选择多个DIV并取消选择,选择最多四个Div仅这些是条件。 我在React-js的初学者是我的div,

<div className='todoDiv select'>Task1</div>
<div className='todoDiv'>Task2</div>
<div className='todoDiv'>Task3</div>
<div className='todoDiv'>Task4</div>
<div className='todoDiv'>Task5</div>

这里选择 class用于突出显示DIV,如何解决这个问题,我在React-js中拥有基本知识,请帮助我

In react-js click a div that div will highlight and click again it will normal, we select multiple div and unselect, select maximum four div only these are the conditions.
I beginner in react-js my div are ,

<div className='todoDiv select'>Task1</div>
<div className='todoDiv'>Task2</div>
<div className='todoDiv'>Task3</div>
<div className='todoDiv'>Task4</div>
<div className='todoDiv'>Task5</div>

here select class is used to highlight the div, how to solve this problem i have basic knowledge in react-js please help me

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

无名指的心愿 2025-02-13 21:07:26

我将通过 usestate(usestate(usestate() ,并维护每个待办事项属性的属性。当单击戒酒时,所选属性会更改。

要将选择限制为4,只需添加一个与以下类似计数的支票。

import React, { useState } from "react";
import ReactDOM from "react-dom";

function App() {
  const [todos, setTodos] = useState([
    { id: "1", name: "Task 1", selected: true },
    { id: "2", name: "Task 2", selected: false },
    { id: "3", name: "Task 3", selected: false },
    { id: "4", name: "Task 4", selected: false },
    { id: "5", name: "Task 5", selected: false }
  ]);

  const todoClicked = (e) => {
    // max 4 selected
    if (!e.target.classList.contains("selected")) {
      const selectedCount = todos.filter((todo) => todo.selected).length;
      if (selectedCount === 4) {
        return;
      }
    }

    setTodos(
      todos.map((todo) =>
        todo.id === e.target.getAttribute("data-id")
          ? { ...todo, selected: !todo.selected }
          : todo
      )
    );
  };

  return (
    <div>
      {todos.map((todo) => (
        <div
          onClick={todoClicked}
          data-id={todo.id}
          key={todo.id}
          className={`todoDiv${todo.selected ? " selected" : ""}`}
        >
          {todo.name}
        </div>
      ))}
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById("container"));

I'd approach this by storing an array of todo objects in state with useState(), and maintain a selected property for each todo. As the todos are clicked, the selected property is changed.

To limit the selections to 4, simply add a check with a count like below.

CodeSandbox demo

import React, { useState } from "react";
import ReactDOM from "react-dom";

function App() {
  const [todos, setTodos] = useState([
    { id: "1", name: "Task 1", selected: true },
    { id: "2", name: "Task 2", selected: false },
    { id: "3", name: "Task 3", selected: false },
    { id: "4", name: "Task 4", selected: false },
    { id: "5", name: "Task 5", selected: false }
  ]);

  const todoClicked = (e) => {
    // max 4 selected
    if (!e.target.classList.contains("selected")) {
      const selectedCount = todos.filter((todo) => todo.selected).length;
      if (selectedCount === 4) {
        return;
      }
    }

    setTodos(
      todos.map((todo) =>
        todo.id === e.target.getAttribute("data-id")
          ? { ...todo, selected: !todo.selected }
          : todo
      )
    );
  };

  return (
    <div>
      {todos.map((todo) => (
        <div
          onClick={todoClicked}
          data-id={todo.id}
          key={todo.id}
          className={`todoDiv${todo.selected ? " selected" : ""}`}
        >
          {todo.name}
        </div>
      ))}
    </div>
  );
}

ReactDOM.render(<App />, document.getElementById("container"));
夜空下最亮的亮点 2025-02-13 21:07:26

在ReactJ中,我们使用状态跟踪和呈现组件的视图。在您的情况下,我们可以创建一个称为“选择的状态”,该状态可维护所选任务的列表。

import React, {useState, useEffect} from 'react';
import './App.css';

function App() {
  const [selected, setSelected] = useState([])
  const updateSelected = (task) => {
    if(!selected.includes(task) && selected.length < 4) {
      let newSelected = [...selected, task];
      setSelected(newSelected)
    } else {
      let newSelected = selected.filter(t => t !== task)
      setSelected(newSelected)
    }
  }
  let tasks = ["Task1", "Task2", "Task3", "Task4", "Task5"]
  return (
    <main>
      {
        tasks.map(task => (
          <div onClick={() => updateSelected(task)} className={`todoDiv ${selected.includes(task) ? 'select' : ''}`}>{task}</div>
        ))
      }
      {`selected = ${selected.join(", ")}`}
    </main>
  );
}

export default App;

最初,它是空的。当用户单击任务时,将其添加到选定任务的列表中。在更新中,我们实现了所需的逻辑,如上所示。在每个任务的className中注意我们使用Javescript模板字符串。如果用户选择了类名,这有助于我们将“选定”类“选择”添加到类名称。

In Reactjs, we use state to keep track of and render the view of the component. In your case, we can create a state called selected which maintains the list of selected tasks.

import React, {useState, useEffect} from 'react';
import './App.css';

function App() {
  const [selected, setSelected] = useState([])
  const updateSelected = (task) => {
    if(!selected.includes(task) && selected.length < 4) {
      let newSelected = [...selected, task];
      setSelected(newSelected)
    } else {
      let newSelected = selected.filter(t => t !== task)
      setSelected(newSelected)
    }
  }
  let tasks = ["Task1", "Task2", "Task3", "Task4", "Task5"]
  return (
    <main>
      {
        tasks.map(task => (
          <div onClick={() => updateSelected(task)} className={`todoDiv ${selected.includes(task) ? 'select' : ''}`}>{task}</div>
        ))
      }
      {`selected = ${selected.join(", ")}`}
    </main>
  );
}

export default App;

Initally, it is empty. When the user clicks on a task, it is added to the list of selected tasks. In the updateSelected, we implement required logic as shown above. Notice in the className for each task we use JaveScript template strings. This helps us to conditionally add class 'selected' to the className if it is selected by the user.

情深已缘浅 2025-02-13 21:07:26

我添加了 task_list 以动态渲染Div。这里 toggletask 函数将选择&amp;去选择Div。正如您所说,最多将选择四个Div。

import { Fragment, useState } from "react";

const TASK_LIST = [1, 2, 3, 4, 5];

export default function MultiSelect() {
  const [selectedTask, selectTask] = useState([]);

  const isSelected = (taskId) => {
    return selectedTask.filter((task) => task === taskId).length;
  };

  const toggleTask = (taskId) => {
    if (isSelected(taskId)) {
      // deselect div
      selectTask((tasks) => tasks.filter((ts) => ts !== taskId));
    } else if (selectedTask.length < 4) {
      // select div, max four div will be selected
      selectTask((tasks) => [...tasks, taskId]);
    }
  };

  return (
    <Fragment>
      {TASK_LIST.map((task) => (
        <div
          className={`todoDiv${isSelected(task) ? " select" : ""}`}
          key={task}
          onClick={() => toggleTask(task)}
        >
          Task{task}
        </div>
      ))}
    </Fragment>
  );
}

I have added a TASK_LIST to dynamically render the div. Here toggleTask function will both select & de-select the div. And as you said, maximum of four div will be selected.

import { Fragment, useState } from "react";

const TASK_LIST = [1, 2, 3, 4, 5];

export default function MultiSelect() {
  const [selectedTask, selectTask] = useState([]);

  const isSelected = (taskId) => {
    return selectedTask.filter((task) => task === taskId).length;
  };

  const toggleTask = (taskId) => {
    if (isSelected(taskId)) {
      // deselect div
      selectTask((tasks) => tasks.filter((ts) => ts !== taskId));
    } else if (selectedTask.length < 4) {
      // select div, max four div will be selected
      selectTask((tasks) => [...tasks, taskId]);
    }
  };

  return (
    <Fragment>
      {TASK_LIST.map((task) => (
        <div
          className={`todoDiv${isSelected(task) ? " select" : ""}`}
          key={task}
          onClick={() => toggleTask(task)}
        >
          Task{task}
        </div>
      ))}
    </Fragment>
  );
}
长发绾君心 2025-02-13 21:07:26
/* Start by defiinig a variable 'divState' to save the state of
   your divs and a function 'setDivState' sto modify that state.
   
   The state variable 'divState' eventually will look like this:
   
   {
      div1: false,
      div2: true,
      div3: false,
      ...
   }
*/
const [divState, setDivState] = useState({})

// we will use this function to update a div state:
const updateState = (id) => {
    setDivState(prevState =>
        ({
            ...prevState, // keep the other divs as they are rught now
            [`div${item}`]: !prevState[`div${item}`] // update the current
            // div's
            // state
        }))
}

// Now we will render the divs, as many as you want
// I will use a the map function to iterate over an array of 4 divs
{
    [1, 2, 3, 4].map(item => (
        <div
            className={`todoDiv ${divState[`div${item}`] ? 'select' : ''}`} // assign
            // class dynamically depending on the current div's state
            onClick={() => updateState(item)}>
            {/* render something inside the divs */}
        </div>
    ))
}

一个完整的组件示例:

import React, {useState} from 'react';

const YourComponent = () => {
    /* Start by defiinig a variable 'divState' to save the state of
       your divs and a function 'setDivState' sto modify that state.
       
       The state variable 'divState' eventually will look like this:
       
       {
          div1: false,
          div2: true,
          div3: false,
          ...
       }
    */
    const [divState, setDivState] = useState({})

// we will use this function to update a div state:
    const updateState = (id) => {
        setDivState(prevState =>
            ({
                ...prevState, // keep the other divs as they are rught now
                [`div${item}`]: !prevState[`div${item}`] // update the current
                // div's
                // state
            }))
    }

// Now we will render the divs, as many as you want
// I will use a the map function to iterate over an array of 4 divs
    return (
        <>  {
            [1, 2, 3, 4].map(item => (
                <div
                    {/* assign class dynamically depending on the current
                     div's state */}
                    className={`todoDiv ${divState[`div${item}`] ? 'select' : ''}`}
                    onClick={() => updateState(item)}>
                    {/* render something inside the divs */}
                </div>
            ))
        }
        </>
    )
}

/* Start by defiinig a variable 'divState' to save the state of
   your divs and a function 'setDivState' sto modify that state.
   
   The state variable 'divState' eventually will look like this:
   
   {
      div1: false,
      div2: true,
      div3: false,
      ...
   }
*/
const [divState, setDivState] = useState({})

// we will use this function to update a div state:
const updateState = (id) => {
    setDivState(prevState =>
        ({
            ...prevState, // keep the other divs as they are rught now
            [`div${item}`]: !prevState[`div${item}`] // update the current
            // div's
            // state
        }))
}

// Now we will render the divs, as many as you want
// I will use a the map function to iterate over an array of 4 divs
{
    [1, 2, 3, 4].map(item => (
        <div
            className={`todoDiv ${divState[`div${item}`] ? 'select' : ''}`} // assign
            // class dynamically depending on the current div's state
            onClick={() => updateState(item)}>
            {/* render something inside the divs */}
        </div>
    ))
}

A complete component example:

import React, {useState} from 'react';

const YourComponent = () => {
    /* Start by defiinig a variable 'divState' to save the state of
       your divs and a function 'setDivState' sto modify that state.
       
       The state variable 'divState' eventually will look like this:
       
       {
          div1: false,
          div2: true,
          div3: false,
          ...
       }
    */
    const [divState, setDivState] = useState({})

// we will use this function to update a div state:
    const updateState = (id) => {
        setDivState(prevState =>
            ({
                ...prevState, // keep the other divs as they are rught now
                [`div${item}`]: !prevState[`div${item}`] // update the current
                // div's
                // state
            }))
    }

// Now we will render the divs, as many as you want
// I will use a the map function to iterate over an array of 4 divs
    return (
        <>  {
            [1, 2, 3, 4].map(item => (
                <div
                    {/* assign class dynamically depending on the current
                     div's state */}
                    className={`todoDiv ${divState[`div${item}`] ? 'select' : ''}`}
                    onClick={() => updateState(item)}>
                    {/* render something inside the divs */}
                </div>
            ))
        }
        </>
    )
}

夜光 2025-02-13 21:07:26

您可以将样式放入类似的变量中,

const [style, setStyle] = useState({ "--my-css-var": 10 })

然后将其放在Div中,

<div style={style}>...</div>

然后将其放在Div上,在DIV上创建一个更改“样式”变量的函数。 样式变量的状态

<div style={style} onClick={() => setStyle({"--my-css-var": 12})}>...</div>

更改您获得JIST的

you can put styles in a variable like so

const [style, setStyle] = useState({ "--my-css-var": 10 })

Then put this in your div like so

<div style={style}>...</div>

Then, create a function onClick on the div that changes the "style" variable. Change the state of the the style variable

<div style={style} onClick={() => setStyle({"--my-css-var": 12})}>...</div>

You get the jist

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文