如何传递每个组件id

How to pass each component id

我想实现拖动组件(漂亮的dnd),以便用户可以交换它们。但是为此,据我了解,每个组件都必须有一个 id。但是我不知道怎么做

import React from 'react';
import CardWeather from '../cardWeather/CardWeather';
import WeatherMap from '../cardWeatherMap/WeatherMap';
import Forecast from '../forecast/Forecast';
import WeatherGrapth from '../weatherGraph/WeatherGraph';
import './main.scss';
import { Droppable } from 'react-beautiful-dnd';

const Main = () => {

    return (
      <>
      <Droppable droppableId="main">
        {
          (provided) => (
            <div className="main-container"
            ref={provided.innerRef} 
            {...provided.droppableProps}
            >
            <CardWeather />
            <Forecast/>
            <WeatherGrapth/>
            <WeatherMap/>
        </div>
          )
        }

      </Droppable>


        <div className="pr">weather app</div>
        </>
    )
}

export default Main;

如果我理解正确,您需要为您的案例中的每个组件提供某种 ID:

 <CardWeather />
 <Forecast/>
 <WeatherGrapth/>
 <WeatherMap/>

您可以为每个组件通过 props 传递 id。示例:

主要成分:

  <CardWeather id="1" />

CardWeather 组件:

function CardWeather(props){
  const id = props.id
  ...
  return(
    <div data-id={id}>
    ...
    </div>
  )
}
...

而且您必须为每个要拖放的组件执行此操作。

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true"> <div class="snippet-code"> <pre><code>import React from 'react'; import CardWeather from '../cardWeather/CardWeather'; import WeatherMap from '../cardWeatherMap/WeatherMap'; import Forecast from '../forecast/Forecast'; import WeatherGrapth from '../weatherGraph/WeatherGraph'; import './main.scss'; import { Droppable, Draggable } from 'react-beautiful-dnd'; import uuid from 'react-uuid'; const Main = () => { return ( <> <Droppable droppableId="main"> { (provided) => ( <Draggable draggableId={uuid()} index={"element index"} > {(provided, snapshot) => { <div className="main-container" ref={provided.innerRef} {...provided.droppableProps} isDragging={snapshot.isDragging} > <CardWeather /> <Forecast /> <WeatherGrapth /> <WeatherMap /> </div> }} </Draggable> ) } </Droppable> <div className="pr">weather app</div> </> ) } export default Main;
<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>

最好每个组件也有一个关键道具。这样一来,如果我进行更改,您将获得重新渲染。