react-beautiful-dnd谷歌翻译中文文档

in js with 0 comment views: 1,312 times

基于谷歌翻译
GitHub:https://github.com/atlassian/react-beautiful-dnd

API

Okay, into the fun stuff - so how do you use the library?

DragDropContext

In order to use drag and drop, you need to have the part of your React tree that you want to be able to use drag and drop in wrapped in a DragDropContext.

为了使用拖放功能,你需要把你想能够拖放的react代码放到DragDropContext中

It is advised to just wrap your entire application in a DragDropContext.

建议将您的整个应用包在DragDropContext中

Having nested DragDropContext's is not supported.

DragDropContext不支持嵌套。

You will be able to achieve your desired conditional dragging and dropping using the props of Droppable and Draggable.

你可以用Droppable和Draggable去实现你想要的拖放操作。

You can think of DragDropContext as having a similar purpose to the react-redux Provider component

您可以将DragDropContext看作是与react-redux Provider组件具有相似的功能

Props

type Hooks = {|
  // optional
  onDragStart?: OnDragStartHook,
  onDragUpdate?: OnDragUpdateHook,
  // always required
  onDragEnd: OnDragEndHook,
|}

type OnDragStartHook = (start: DragStart, provided: HookProvided) => void;
type OnDragUpdateHook = (update: DragUpdate, provided: HookProvided) => void;
type OnDragEndHook = (result: DropResult, provided: HookProvided) => void;

type Props = {|
  ...Hooks,
  children: ?Node,
|}

Basic usage

import { DragDropContext } from 'react-beautiful-dnd';

class App extends React.Component {
  onDragStart = () => {
    /*...*/
  };
  onDragUpdate = () => {
    /*...*/
  }
  onDragEnd = () => {
    // the only one that is required
  };

  render() {
    return (
      <DragDropContext
        onDragStart={this.onDragStart}
        onDragUpdate={this.onDragUpdate}
        onDragEnd={this.onDragEnd}
      >
        <div>Hello world</div>
      </DragDropContext>
    );
  }
}

Hooks

These are top level application events that you can use to perform your own state updates as well as to make screen reader announcements. For more information about controlling the screen reader see our screen reader guide

这些是顶级应用程序事件,您可以使用它来执行自己的状态更新以及制作屏幕阅读器公告。
有关控制屏幕阅读器的更多信息,请参阅屏幕阅读器指南

provided: HookProvided

type HookProvided = {|
  announce: Announce,
|}

type Announce = (message: string) => void;

All hooks are provided with a second argument: HookProvided. This object has one property: announce. This function is used to synchronously announce a message to screen readers. If you do not use this function we will announce a default english message. We have created a guide for screen reader usage which we recommend using if you are interested in controlling the screen reader messages for yourself and to support internationalisation. If you are using announce it must be called synchronously.

所有钩子都提供了第二个参数:HookProvided。
该对象有一个属性:announce。
此功能用于同步向屏幕阅读器发布消息。
如果你不使用这个功能,我们会宣布一个默认的英文信息。
如果您有兴趣为自己控制屏幕阅读器信息并支持国际化,我们建议使用我们推荐使用的屏幕阅读器使用指南。
如果您使用announce,则必须同步调用。

onDragStart (optional)

type OnDragStartHook = (start: DragStart, provided: HookProvided) => void;

onDragStart will get notified when a drag starts. This hook is optional and therefore does not need to be provided. It is highly recommended that you use this function to block updates to all Draggable and Droppable components during a drag. (See Best practices for hooks )

onDragStart将在拖动开始时得到通知。
该钩子是可选的,因此不需要提供。
强烈建议您在拖动过程中使用此功能来阻止对所有可拖拽组件和可拖拽组件的更新。

You are provided with the following details:

您将获得以下详细信息:

start: DragStart

type DragStart = {|
  draggableId: DraggableId,
  type: TypeId,
  source: DraggableLocation,
|}

onDragStart type information

type OnDragStartHook = (start: DragStart, provided: HookProvided) => void;

// supporting types
type DragStart = {|
  draggableId: DraggableId,
  type: TypeId,
  source: DraggableLocation,
|}

type DraggableLocation = {|
  droppableId: DroppableId,
  // the position of the draggable within a droppable
  index: number
|};
type Id = string;
type DraggableId = Id;
type DroppableId = Id;
type TypeId = Id;

onDragUpdate (optional)

type OnDragUpdateHook = (update: DragUpdate, provided: HookProvided) => void;

This hook is called whenever something changes during a drag. The possible changes are:

只要拖动过程中发生某些变化,就会调用该钩子。
可能的变化是:

It is important that you not do too much work as a result of this function as it will slow down the drag.

由于此功能,您不需要做太多工作,因为它会减慢阻力。

update: DragUpdate

type DragUpdate = {|
  ...DragStart,
  // may not have any destination (drag to nowhere)
  destination: ?DraggableLocation,
|}

onDragEnd (required)

This function is extremely important and has an critical role to play in the application lifecycle. This function must result in the synchronous reordering of a list of Draggables

此功能非常重要,并且在应用程序生命周期中扮演至关重要的角色。该函数必须导致Draggable列表的同步重新排序

It is provided with all the information about a drag:

它提供了有关拖动的所有信息:

result: DropResult

type DropResult = {|
  ...DragUpdate,
  reason: DropReason,
|}

type DropReason = 'DROP' | 'CANCEL';

Synchronous reordering (同步重新排序)

Because this library does not control your state, it is up to you to synchronously reorder your lists based on the result: DropResult.

由于该库不能控制您的状态,因此您需要根据结果同步重新排列列表:DropResult。

Here is what you need to do (这是你需要做的)

Persisting a reorder(坚持重新排序)

If you need to persist a reorder to a remote data store - update the list synchronously on the client and fire off a request in the background to persist the change. If the remote save fails it is up to you how to communicate that to the user and update, or not update, the list.

如果您需要将重新排序保留到远程数据存储区 - 在客户端上同步更新列表,并在后台触发请求以保持更改。如果远程保存失败,则由您决定如何与用户通信并更新或不更新列表。

Best practices for hooks (钩子的最佳实践)

Block updates during a drag (在拖动过程中阻止更新)

It is highly recommended that while a user is dragging that you block any state updates that might impact the amount of Draggables and Droppables, or their dimensions. Please listen to onDragStart and block updates to the Draggables and Droppables until you receive at onDragEnd.

强烈建议用户在拖动时阻止任何可能影响Draggables和Droppables数量或其维度的状态更新。请收听onDragStart并阻止对Draggables和Droppables的更新,直到您在onDragEnd收到为止。

When the user starts dragging we take a snapshot of all of the dimensions of the applicable Draggable and Droppable nodes. If these change during a drag we will not know about it.

当用户开始拖动时,我们拍摄适用的Draggable和Droppable节点的所有维度的快照。如果在拖动过程中这些变化我们不会知道。

How do you block updates? (你如何阻止更新?)

Update blocking will look different depending on how you manage your data. It is probably best to explain by example:

取决于您如何管理数据,更新阻止会有所不同。这可能是最好的例子解释:

Let's say you are using React component state to manage the state of your application. Your application state is tied to a REST endpoint that you poll every thirty seconds for data updates. During a drag you should not apply any server updates that could effect what is visible.

假设您正在使用React组件状态来管理应用程序的状态。您的应用程序状态与您每隔三十秒轮询一次数据更新的REST端点相关联。在拖动过程中,您不应该应用任何可能会影响可见效果的服务器更新。

This could mean:

这可能意味着:

No update blocking can lead to bad times (没有更新阻止会导致不好的时间)

Here are a few poor user experiences that can occur if you change things during a drag:

如果您在拖动过程中更改某些内容,可能会出现一些糟糕的用户体验:

onDragStart and onDragEnd pairing (onDragStart和onDragEnd配对)

We try very hard to ensure that each onDragStart event is paired with a single onDragEnd event. However, there maybe a rogue situation where this is not the case. If that occurs - it is a bug. Currently there is no mechanism to tell the library to cancel a current drag externally.

我们非常努力地确保每个onDragStart事件都与一个onDragEnd事件配对。但是,在这种情况下可能会出现流氓情况。如果发生这种情况 - 这是一个错误。目前没有任何机制可以告诉图书馆从外部取消当前的拖拽。

Droppable

Droppable components can be dropped on by a Draggable. They also contain Draggables. A Draggable must be contained within a Droppable.

可拖放的组件可以通过Draggable拖放。它们也包含Draggables。Draggable必须包含在Droppable中

import { Droppable } from 'react-beautiful-dnd';

<Droppable droppableId="droppable-1" type="PERSON">
  {(provided, snapshot) => (
    <div
      ref={provided.innerRef}
      style={{ backgroundColor: snapshot.isDraggingOver ? 'blue' : 'grey' }}
      {...provided.droppableProps}
    >
      <h2>I am a droppable!</h2>
      {provided.placeholder}
    </div>
  )}
</Droppable>;

Droppable props

Children function

The React children of a Droppable must be a function that returns a ReactElement.

Droppable的React子元素必须是返回ReactElement的函数。

<Droppable droppableId="droppable-1">
  {(provided, snapshot) => ({
    /*...*/
  })}
</Droppable>;

The function is provided with two arguments:

该函数提供了两个参数

1. provided: (DroppableProvided)**

type DroppableProvided = {|
  innerRef: (?HTMLElement) => void,
  droppableProps: DroppableProps,
  placeholder: ?ReactElement,
|}

type DroppableProps = {|
  // used for shared global styles
  'data-react-beautiful-dnd-droppable': string,
|}
<Droppable droppableId="droppable-1">
  {(provided, snapshot) => (
    <div ref={provided.innerRef} {...provided.droppableProps}>
      Good to go

      {provided.placeholder}
    </div>
  )}
</Droppable>;

2. snapshot: (DroppableStateSnapshot)**

type DroppableStateSnapshot = {|
  // Is the Droppable being dragged over?
  isDraggingOver: boolean,
  // What is the id of the draggable that is dragging over the Droppable?
  draggingOverWith: ?DraggableId,
|};

The children function is also provided with a small amount of state relating to the current drag state. This can be optionally used to enhance your component. A common use case is changing the appearance of a Droppable while it is being dragged over.

儿童功能还提供与当前拖动状态有关的少量状态。这可以选择用于增强组件。一个常见的用例是在被拖动时改变Droppable的外观。

<Droppable droppableId="droppable-1">
  {(provided, snapshot) => (
    <div
      ref={provided.innerRef}
      style={{ backgroundColor: snapshot.isDraggingOver ? 'blue' : 'grey' }}
      {...provided.droppableProps}
    >
      I am a droppable!

      {provided.placeholder}
    </div>
  )}
</Droppable>;

Conditionally dropping

Scroll containers

This library supports dragging within scroll containers (DOM elements that have overflow: auto; or overflow: scroll;). The only supported use cases are:

该库支持在滚动容器(具有溢出的DOM元素:自动;或溢出:滚动;)内拖动。唯一支持的用例是:

  1. The Droppable can itself be a scroll container with no scrollable parents

Droppable本身可以是一个没有可滚动父母的滚动容器

  1. The Droppable has one scrollable parent

Droppable有一个可滚动的父项

where a scrollable parent refers to a scroll container that is not the window itself.

一个可滚动的父级指的是一个不是窗口本身的滚动容器。

Empty Droppables

It is recommended that you put a min-height on a vertical Droppable or a min-width on a horizontal Droppable. Otherwise when the Droppable is empty there may not be enough of a target for Draggable being dragged with touch or mouse inputs to be over the Droppable.

建议您在垂直Droppable上放置最小高度,或者在水平Droppable上放置最小宽度。否则,当Droppable为空时,可能没有足够的Draggable通过触摸或鼠标输入拖动到Droppable上。

Recommended Droppable performance optimisation (推荐Droppable性能优化)

When a user drags over, or stops dragging over, a Droppable we re-render the Droppable with an updated DroppableStateSnapshot > isDraggingOver value. This is useful for styling the Droppable. However, by default this will cause a render of all of the children of the Droppable - which might be 100's of Draggables! This can result in a noticeable frame rate drop. To avoid this problem we recommend that you create a component that is the child of a Droppable who's responsibility it is to avoid rendering children if it is not required.

当用户拖拽或停止拖拽时,我们可以使用更新的DroppableStateSnapshot> isDraggingOver值重新呈现Droppable。这对于Droppable的造型很有用。但是,默认情况下,这将导致Droppable的所有子项的渲染 - 可能是100个Draggable!这可能导致明显的帧速下降。为了避免这个问题,我们建议您创建一个组件,该组件是Droppable的子组件,它负责避免在不需要时呈现子组件。

Here is an example of how you could do this:

以下是你如何做到这一点的例子:

import React, { Component } from 'react';

class Student extends Component<{ student: Person }> {
  render() {
    // Renders out a draggable student
  }
}

class InnerList extends Component<{ students: Person[] }> {
  // do not re-render if the students list has not changed
  shouldComponentUpdate(nextProps: Props) {
    if(this.props.students === nextProps.students) {
      return false;
    }
    return true;
  }
  // You could also not do your own shouldComponentUpdate check and just
  // extend from React.PureComponent

  render() {
    return this.props.students.map((student: Person) => (
      <Student student={student} />
    ))
  }
}

class Students extends Component {
  render() {
    return (
      <Droppable droppableId="list">
        {(provided: DroppableProvided, snapshot: DroppableStateSnapshot) => (
          <div
            ref={provided.innerRef}
            style={{ backgroundColor: provided.isDragging ? 'green' : 'lightblue' }}
            {...provided.droppableProps}
          >
            <InnerList students={this.props.students} />
            {provided.placeholder}
          </div>
        )}
      </Droppable>
    )
  }
}

By using the approach you are able to make style changes to a Droppable when it is being dragged over, but you avoid re-rendering all of the children unnecessarily. Keep in mind that if you are using React.PureComponent that your component will not respond to changes in the context.

通过使用该方法,您可以在拖动时拖放样式,但避免不必要地重新渲染所有的孩子。请记住,如果您使用React.PureComponent,您的组件将不会响应上下文中的更改。

Unfortunately we are unable to apply this optimisation for you. It is a byproduct of using the function-as-child pattern.

不幸的是,我们无法为您应用此优化。它是使用函数作为子模式的副产品。

Draggable

Draggable components can be dragged around and dropped onto Droppables. A Draggable must always be contained within a Droppable. It is possible to reorder a Draggable within its home Droppable or move to another Droppable. It is possible because a Droppable is free to control what it allows to be dropped on it.

可拖动的组件可以拖动并拖放到Droppables上。Draggable必须始终包含在Droppable中。可以在其家庭Droppable内重新排序Draggable或移动到另一个Droppable。这是可能的,因为Droppable可以自由控制它可以放在它上面的东西。

Every Draggable has a drag handle. A drag handle is the element that the user interacts with in order to drag a Draggable. A drag handle can be a the Draggable element itself, or a child of the Draggable.

每个Draggable都有一个拖动手柄。拖动手柄是用户与之交互以拖动Draggable的元素。拖动手柄可以是Draggable元素本身,也可以是Draggable的子元素。

import { Draggable } from 'react-beautiful-dnd';

<Draggable draggableId="draggable-1" index={0}>
  {(provided, snapshot) => (
    <div
      ref={provided.innerRef}
      {...provided.draggableProps}
      {...provided.dragHandleProps}
    >
      <h4>My draggable</h4>
    </div>
  )}
</Draggable>;

Note: when the library moves to React 16 this will be cleaned up a little bit as we will be able to return the placeholder as a sibling to your child function without you needing to create a wrapping element

注意:当库移动到React 16时,这将被清理一些,因为我们可以将占位符作为兄弟返回到您的子函数,而无需创建包装元素

Draggable Props

{this.props.items.map((item, index) => (
  <Draggable draggableId={item.id} index={index}>
    {(provided, snapshot) => (
      <div ref={provided.innerRef} {...provided.draggableProps}>
        {item.content}
      </div>
    )}
  </Draggable>
))}

Children function (render props)

The React children of a Draggable must be a function that returns a ReactElement.

Draggable的React子项必须是返回ReactElement的函数。

<Draggable draggableId="draggable-1" index={0}>
  {(provided, snapshot) => (
      <div
        ref={provided.innerRef}
        {...provided.draggableProps}
        {...provided.dragHandleProps}
      >
        Drag me!
      </div>
  )}
</Draggable>;

The function is provided with two arguments:

该函数提供了两个参数:

1. provided: (DraggableProvided)**

type DraggableProvided = {|
  innerRef: (HTMLElement) => void,
  draggableProps: DraggableProps,
  // will be null if the draggable is disabled
  dragHandleProps: ?DragHandleProps,
|}

Everything within the provided object must be applied for the Draggable to function correctly.

提供的对象中的所有内容都必须应用于Draggable才能正常运行。

innerRef Example
<Draggable draggableId="draggable-1" index={0}>
  {(provided, snapshot) => <div ref={provided.innerRef}>Drag me!</div>}
</Draggable>;
draggableProps Type information
// Props that can be spread onto the element directly
export type DraggableProps = {|
  // inline style
  style: ?DraggableStyle,
  // used for shared global styles
  'data-react-beautiful-dnd-draggable': string,
|}

type DraggableStyle = DraggingStyle | NotDraggingStyle
type DraggingStyle = {|
  position: 'fixed',
  width: number,
  height: number,
  boxSizing: 'border-box',
  pointerEvents: 'none',
  top: number,
  left: number,
  margin: 0,
  transition: 'none',
  transform: ?string,
  zIndex: ZIndex,
|}
type NotDraggingStyle = {|
  transition: ?string,
  transition: null | 'none',
|}
draggableProps Example
<Draggable draggableId="draggable-1" index={0}>
  {(provided, snapshot) => (
    <div ref={provided.innerRef} {...provided.draggableProps}>
      Drag me!
    </div>
  )}
</Draggable>;
Positioning ownership (定位所有权)

It is a contract of this library that it owns the positioning logic of the dragging element. This includes properties such as top, right, bottom, left and transform. The library may change how it positions things and which properties it uses without performing a major version bump. It is also recommended that you do not apply your own transition property to the dragging element.

它是该库的一个合约,它拥有拖动元素的定位逻辑。这包括诸如top,right,bottom,left和transform之类的属性。图书馆可能会改变它如何定位事物以及它使用的是哪些属性,而不会执行主要的版本冲突。还建议您不要将自己的过渡属性应用于拖动元素。

Warning: position: fixed

react-beautiful-dnd uses position: fixed to position the dragging element. This is quite robust and allows for you to have position: relative | absolute | fixed parents. However, unfortunately position:fixed is impacted by transform (such as transform: rotate(10deg);). This means that if you have a transform: * on one of the parents of a Draggable then the positioning logic will be incorrect while dragging. Lame! For most consumers this will not be an issue.

react-beautiful-dnd使用position:fixed来定位拖动元素。这是相当强大的,并允许你有位置:relative |绝对|固定的父母。然而,不幸的是position:fixed受到变换的影响(如transform:rotate(10deg);)。这意味着,如果您在Draggable的某个父项中有一个变换:*,则在拖动时定位逻辑将不正确。瘸!对于大多数消费者来说,这不会是一个问题。

To get around this you can use React.Portal. We do not enable this functionality by default as it has performance problems. We have a using a portal guide explaining the performance problem in more detail and how you can set up your own React.Portal if you want to.

为了解决这个问题,你可以使用React.Portal。我们不会默认启用此功能,因为它有性能问题。我们有一个使用门户指南,更详细地解释性能问题,以及如何设置自己的React.Portal。

Focus retention when moving between lists (在列表之间移动时保持焦点)

When moving a Draggable from one list to another the default browser behaviour is for the drag handle element to loose focus. This is because the old element is being destroyed and a new one is being created. The loss of focus is not good when dragging with a keyboard as the user is then unable to continue to interact with the element. To improve this user experience we automatically give a drag handle focus when:

将Draggable从一个列表移动到另一个列表时,默认的浏览器行为是为拖动控件元素释放焦点。这是因为旧元素正在被破坏,并且正在创建一个新元素。当用键盘拖动时,焦点丢失并不好,因为用户无法继续与元素交互。为了改善这种用户体验,我们在以下情况下自动给出拖动手柄焦点

Extending DraggableProps.style

If you are using inline styles you are welcome to extend the DraggableProps.style object. You are also welcome to apply the DraggableProps.style object using inline styles and use your own styling solution for the component itself - such as styled-components.

如果您使用内联样式,欢迎您扩展DraggableProps.style对象。您也可以使用内联样式应用DraggableProps.style对象,并为组件本身使用自己的样式解决方案 - 例如样式化组件。

If you are overriding inline styles be sure to do it after you spread the provided.draggableProps or the spread will override your inline style.

如果您重写内联样式,请务必在传播provided.draggableProps之后执行此操作,否则传播将覆盖内联样式。

<Draggable draggable="draggable-1" index={0}>
  {(provided, snapshot) => {
    // extending the DraggableStyle with our own inline styles
    const style = {
      backgroundColor: snapshot.isDragging ? 'blue' : 'white',
      fontSize: 18,
      ...provided.draggableProps.style,
    };
    return (
      <div
        ref={provided.innerRef}
        {...provided.draggableProps}
        style={style}
      >
        Drag me!
      </div>
    );
  }}
</Draggable>;
Avoid margin collapsing between Draggables (避免Draggables之间的边缘折叠)

margin collapsing is one of those really hard parts of CSS. For our purposes, if you have one Draggable with a margin-bottom: 10px and the next Draggable has a margin-top: 12px these margins will collapse and the resulting margin will be the greater of the two: 12px. When we do our calculations we are currently not accounting for margin collapsing. If you do want to have a margin on the siblings, wrap them both in a div and apply the margin to the inner div so they are not direct siblings.

边缘折叠是CSS中非常困难的部分之一。对于我们的目的,如果您有一个边距为10px的Draggable,下一个可拖动的边距为12px,则这些边距将折叠,并且所得的边距将是两个:12px中较大的一个。当我们进行我们的计算时,我们目前没有考虑边缘折叠。如果你想在兄弟姐妹身上有一个边距,将它们都包装在一个div中,并将边距应用到内部div,以使它们不是直接的兄弟姐妹。

Draggables should be visible siblings(Draggables应该是可见的兄弟姐妹)

It is an assumption that Draggables are visible siblings of one another. There can be other elements in between, but these elements should not take up any additional space. You probably will not do this anyway, but just calling it out to be super clear.

这是一个假设,Draggables是彼此可见的兄弟姐妹。中间还可以有其他元素,但这些元素不应占用额外的空间。无论如何,你可能不会这样做,但只要说出来就非常清楚。

// Direct siblings (✔)
<Draggable draggableId="draggable-1" index={0}>
  {() => {}}
</Draggable>
<Draggable draggableId="draggable-2" index={1}>
  {() => {}}
</Draggable>

// Not direct siblings, but are visible siblings (✔)
<div>
  <Draggable draggableId="draggable-1" index={0}>
    {() => {}}
  </Draggable>
</div>
<div>
  <Draggable draggableId="draggable-2" index={1}>
    {() => {}}
  </Draggable>
</div>

// Spacer elements(×)
<Draggable draggableId="draggable-1" index={0}>
    {() => {}}
</Draggable>
<p>I will break things!</p>
<Draggable draggableId="draggable-2" index={1}>
    {() => {}}
</Draggable>

// Spacing on non sibling wrappers(×)
<div style={{padding: 10}}>
  <Draggable draggableId="draggable-1" index={0}>
    {() => {}}
  </Draggable>
</div>
<div style={{padding: 10}}>
  <Draggable draggableId="draggable-2" index={1}>
    {() => {}}
  </Draggable>
</div>
dragHandleProps Type information
type DragHandleProps = {|
  onFocus: () => void,
  onBlur: () => void,
  onMouseDown: (event: MouseEvent) => void,
  onKeyDown: (event: KeyboardEvent) => void,
  onTouchStart: (event: TouchEvent) => void,
  'data-react-beautiful-dnd-drag-handle': string,
  'aria-roledescription': string,
  tabIndex: number,
  draggable: boolean,
  onDragStart: (event: DragEvent) => void,
|}
dragHandleProps Example: standard
<Draggable draggableId="draggable-1" index={0}>
  {(provided, snapshot) => (
    <div
      ref={provided.innerRef}
      {...provided.draggableProps}
      {...provided.dragHandleProps}
    >
      Drag me!
    </div>
  )}
</Draggable>;
dragHandleProps Example: custom drag handle

Controlling a whole draggable by just a part of it

通过它的一部分控制整个可拖动

<Draggable draggableId="draggable-1" index={0}>
  {(provided, snapshot) => (
    <div ref={provided.innerRef} {...provided.draggableProps}>
      <h2>Hello there</h2>
      <div {...provided.dragHandleProps}>Drag handle</div>
    </div>
  )}
</Draggable>;
dragHandleProps monkey patching

You can override some of the dragHandleProps props with your own behavior if you need to.

如果需要,可以用自己的行为重写一些dragHandleProps道具。

const myOnMouseDown = event => console.log('mouse down on', event.target);

<Draggable draggableId="draggable-1" index={0}>
  {(provided, snapshot) => {
    const onMouseDown = (() => {
      // dragHandleProps might be null
      if (!provided.dragHandleProps) {
        return onMouseDown;
      }

      // creating a new onMouseDown function that calls myOnMouseDown as well as the drag handle one.
      return (event) => {
        provided.dragHandleProps.onMouseDown(event);
        myOnMouseDown(event);
      };
    })();

    return (
      <div
        ref={provided.innerRef}
        {...provided.draggableProps}
        {...provided.dragHandleProps}
        onMouseDown={onMouseDown}
      >
        Drag me!
      </div>
    );
  }}
</Draggable>;

2. Snapshot: (DraggableStateSnapshot)**

type DraggableStateSnapshot = {|
  isDragging: boolean,
  // What Droppable (if any) the Draggable is currently over
  draggingOver: ?DroppableId,
|};

The children function is also provided with a small amount of state relating to the current drag state. This can be optionally used to enhance your component. A common use case is changing the appearance of a Draggable while it is being dragged. Note: if you want to change the cursor to something like grab you will need to add the style to the draggable. (See Extending DraggableProps.style above)

儿童功能还提供与当前拖动状态有关的少量状态。这可以选择用于增强组件。一个常见的用例是在拖动Draggable时改变其外观。注意:如果您想将光标更改为像抓取一样的东西,您需要将样式添加到可拖动。(请参阅上面的扩展DraggableProps.style)

<Draggable draggableId="draggable-1" index={0}>
  {(provided, snapshot) => {
    const style = {
      backgroundColor: snapshot.isDragging ? 'blue' : 'grey',
      ...provided.draggableProps.style,
    };

    return (
      <div
        ref={provided.innerRef}
        {...provided.draggableProps}
        {...provided.dragHandleProps}
        style={style}
      >
        Drag me!
      </div>
    );
  }}
</Draggable>;

Draggable placeholder

When dragging a Draggable we leave behind a placeholder React.Element to maintain space in the Droppable in order to prevent it from collapsing. The placeholder mimics the styling and layout (including width, height, margin, tagName and display) to ensure the list dimensions remain unaffected while dragging. It will be inserted as a direct sibling to the React.Node returned by the Draggable children function.

拖动Draggable时,我们留下一个占位符React.Element来维护Droppable中的空间,以防止它崩溃。占位符模仿样式和布局(包括宽度,高度,边距,tagName和显示),以确保列表尺寸在拖动时不受影响。它将作为直接兄弟插入到由Draggable子函数返回的React.Node中。

Adding an onClick handler to a Draggable or a drag handle

You are welcome to add your own onClick handler to a Draggable or a drag handle (which might be the same element). onClick events handlers will always be called if a click occurred. If we are preventing the click then we the event.defaultPrevented property will be set to true. We prevent click events from occurring when the user was dragging an item. See #sloppy-clicks-and-click-prevention- for more information.

欢迎您将自己的onClick处理程序添加到Draggable或拖动句柄(可能是相同的元素)。如果发生点击,onClick事件处理程序将始终被调用。如果我们阻止点击,那么我们将event.defaultPrevented属性设置为true。我们阻止用户拖动项目时发生点击事件。请参阅[#sloppy-clicks-and-click-prevention - ](马虎点击和点击预防)了解更多信息。

Interactive child elements within a Draggable (交互式子元素在Draggable中)

It is possible for your Draggable to contain interactive elements. By default we block dragging on these elements. By doing this we allow those elements to function in the usual way. Here is the list of interactive elements that we block dragging from by default:

您的Draggable可能包含交互式元素。默认情况下,我们阻止拖动这些元素。通过这样做,我们允许这些元素以通常的方式运行。以下是默认阻止拖动的交互式元素列表

You can opt out of this behavior by adding the disableInteractiveElementBlocking prop to a Draggable. However, it is questionable as to whether you should be doing so because it will render the interactive element unusable. If you need to conditionally block dragging from interactive elements you can add the disableInteractiveElementBlocking prop to opt out of the default blocking and monkey patch the dragHandleProps (DragHandleProps) event handlers to disable dragging as required.

您可以通过将disableInteractiveElementBlocking prop添加到Draggable中来退出此行为。但是,您是否应该这样做是值得怀疑的,因为它会使交互式元素无法使用。如果您需要有条件地阻止交互式元素的拖动,可以添加disableInteractiveElementBlocking prop来选择不使用默认阻止,并且为dragHandleProps(DragHandleProps)事件处理程序修补程序以禁用所需的拖动操作。

resetServerContext

The resetServerContext function should be used when server side rendering (SSR). It ensures context state does not persist across multiple renders on the server which would result in client/server markup mismatches after multiple requests are rendered on the server.

在服务器端呈现(SSR)时应使用resetServerContext函数。它确保上下文状态不会在服务器上的多个呈现中持续存在,这会在服务器上呈现多个请求后导致客户端/服务器标记不匹配。

Use it before calling the server side render method:

在调用服务器端渲染方法之前使用它:

import { resetServerContext } from 'react-beautiful-dnd';
import { renderToString } from 'react-dom/server';

...

resetServerContext();
renderToString(...);

Flow usage

react-beautiful-dnd is typed using flowtype. This greatly improves internal consistency within the codebase. We also expose a number of public types which will allow you to type your javascript if you would like to. If you are not using flowtype this will not inhibit you from using the library. It is just extra safety for those who want it.

react-beautiful-dnd是使用flowtype键入的。这大大提高了代码库内部的一致性。我们还公开了许多公共类型,如果您愿意,可以输入您的javascript。如果您不使用流量类型,这不会阻止您使用该库。对于那些想要它的人来说,这只是额外的安全。

Public flow types

// id's
type Id = string;
type TypeId = Id;
type DroppableId = Id;
type DraggableId = Id;

// hooks
type DragStart = {|
  draggableId: DraggableId,
  type: TypeId,
  source: DraggableLocation,
|}

type DragUpdate = {|
  ...DragStart,
  // may not have any destination (drag to nowhere)
  destination: ?DraggableLocation,
|}

type DropResult = {|
  ...DragUpdate,
  reason: DropReason,
|}

type DropReason = 'DROP' | 'CANCEL'

type DraggableLocation = {|
  droppableId: DroppableId,
  // the position of the droppable within a droppable
  index: number
|};

// Droppable
type DroppableProvided = {|
  innerRef: (?HTMLElement) => void,
  placeholder: ?ReactElement,
|}

type DroppableStateSnapshot = {|
  isDraggingOver: boolean,
  draggingOverWith: ?DraggableId,
|}

// Draggable
type DraggableProvided = {|
  innerRef: (?HTMLElement) => void,
  draggableProps: DraggableProps,
  dragHandleProps: ?DragHandleProps,
|}

type DraggableStateSnapshot = {|
  isDragging: boolean,
  draggingOver: ?DroppableId,
|}

export type DraggableProps = {|
  style: ?DraggableStyle,
  'data-react-beautiful-dnd-draggable': string,
|}
type DraggableStyle = DraggingStyle | NotDraggingStyle
type DraggingStyle = {|
  position: 'fixed',
  width: number,
  height: number,
  boxSizing: 'border-box',
  pointerEvents: 'none',
  top: number,
  left: number,
  margin: 0,
  transition: 'none',
  transform: ?string,
  zIndex: ZIndex,
|}
type NotDraggingStyle = {|
  transition: ?string,
  transition: null | 'none',
|}

type DragHandleProps = {|
  onFocus: () => void,
  onBlur: () => void,
  onMouseDown: (event: MouseEvent) => void,
  onKeyDown: (event: KeyboardEvent) => void,
  onTouchStart: (event: TouchEvent) => void,
  'data-react-beautiful-dnd-drag-handle': string,
  'aria-roledescription': string,
  tabIndex: number,
  draggable: boolean,
  onDragStart: (event: DragEvent) => void,
|}

Using the flow types

The types are exported as part of the module so using them is as simple as:

这些类型作为模块的一部分导出,因此使用它们非常简单:

import type { DroppableProvided } from 'react-beautiful-dnd';
Responses