gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 13:45:03 24 4
gpt4 key购买 nike

我无法找到这个 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com