简体   繁体   English

上下移动组件

[英]moving components up and down

I have a simple project.我有一个简单的项目。

I want to move components up and down with buttons.我想用按钮上下移动组件。 How can I do that?我怎样才能做到这一点?

for example;例如; https://codesandbox.io/s/epic-water-k1m4fg https://codesandbox.io/s/epic-water-k1m4fg

import React, { useState } from "react";

function arraymove(arr, fromIndex, toIndex) {
  const arrCopy = [...arr];
  var element = arrCopy[fromIndex];
  arrCopy.splice(fromIndex, 1);
  arrCopy.splice(toIndex, 0, element);

  return arrCopy;
}

export default function App() {
  const [components, setComponents] = useState([]);

  function MoveUp(index) {
    if (index === 0) return;

    const updatedArray = arraymove(components, index, index - 1);
    setComponents(updatedArray);
  }

  function MoveDown(index) {
    if (index === components.length - 1) return;

    const updatedArray = arraymove(components, index, index + 1);
    setComponents(updatedArray);
  }

  const MovableComponent = (props) => (
    <>
      <div>{props.id}</div>
      <button onClick={() => MoveUp(props.index)}> Move Up </button>
      <button onClick={() => MoveDown(props.index)}> Move Down </button>
      <br />
      <br />
    </>
  );

  return (
    <div className="App">
      {components.map(({ id }, index) => (
        <MovableComponent key={index} id={id} index={index} />
      ))}
      <button
        onClick={() => {
          setComponents((prev) => [
            ...prev,
            { id: `component #${components.length}` }
          ]);
        }}
      >
        Add
      </button>
    </div>
  );
}

Codesandbox 代码沙盒

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM