reactjs - 请向我解释一下这个奇怪的 React 语法

标签 reactjs

我无法找到这个 React 语法的含义:

useRef<Position[]>([]).current

我试图理解在函数中找到的一些代码:

export const Example = () => {
  const [colors, setColors] = useState(initialColors);

  // We need to collect an array of height and position data for all of this component's
  // `Item` children, so we can later us that in calculations to decide when a dragging
  // `Item` should swap places with its siblings.
  const positions = useRef<Position[]>([]).current;
  const setPosition = (i: number, offset: Position) => (positions[i] = offset);

  // Find the ideal index for a dragging item based on its position in the array, and its
  // current drag offset. If it's different to its current index, we swap this item with that
  // sibling.
  const moveItem = (i: number, dragOffset: number) => {
    const targetIndex = findIndex(i, dragOffset, positions);
    if (targetIndex !== i) setColors(move(colors, i, targetIndex));
  };

  return (
    <ul>
      {colors.map((color, i) => (
        <Item
          key={color}
          i={i}
          color={color}
          setPosition={setPosition}
          moveItem={moveItem}
        />
      ))}
    </ul>
  );
};

代码在 codesandbox example 中在Example.tsx中。

最佳答案

这是一个 typescript 代码,其含义是:

const positions = useRef<Position[]>([]).current

嘿,给我一个 Position[] 类型的引用 (React.useRef)(Positions 数组),初始化它的 current 属性,带有空数组 [] 并将 current 分配给名为 positionsconst。所以当你这样做时:

console.log(positions) // []

关于reactjs - 请向我解释一下这个奇怪的 React 语法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57328407/

相关文章:

node.js - Webpack 失败,babel 已移至 babel-core

reactjs - 如何将状态对象表示为 typescript 接口(interface)

reactjs - react 路由器和上下文类型

html - 在 react 中导入图像有问题

reactjs - 使用 React + Material UI Card Expander 扩展单个卡片

javascript - 机器人会在 React ComponentDidMount 中运行代码吗?

reactjs - 使用 webpack、ES6、ReactJS 导入 JavaScript 文件并调用函数

javascript - 如何使用带有私有(private)路由的react-router-dom避免刷新页面时分页?

reactjs - React 动态默认 props

javascript - react Redux : Posting Records partly work with onclick function