反应:我可以在不引起重画的情况下更改状态(useState),以便可以看到CSS转换吗?

问题描述 投票:0回答:1

我有不同的“卡片”,它们单击onClick时就希望对其margin-left属性进行修改

为此,我使用useState,对于该状态我只有一个状态,该状态是存储所有卡的状态的对象

下面的示例代码显示了问题,但是没有组件<Type>且使用简单的elements数组的简化版本可以正常工作

因此,如果需要使用以下结构,如何保持过渡效果?

示例代码

https://codesandbox.io/s/keen-shadow-2v16s?fontsize=14&hidenavigation=1&theme=dark

import React, { useState } from "react";
import styled from "@emotion/styled";

export default function App() {
  const [userTap, setUserTap] = useState({});
  const elements1 = [...Array(5)];
  const elements2 = [...Array(3)];

  const Type = ({ list }) =>
    list.map((el, i) => (
      <Ingredient
        key={"draggable" + i}
        onClick={e => {
          e.stopPropagation();
          e.preventDefault();
          userTap[i] = userTap[i] ? 0 : 1;
          setUserTap({ ...userTap }); // create a new ref to provoke the rerender
          return;
        }}
        userTap={userTap[i]}
      >
        <div>item</div>
      </Ingredient>
    ));

  return (
    <>
      <Type list={elements1} />
      <Type list={elements2} />
    </>
  );
}

const Ingredient = styled.li`
  list-style: none;
  cursor: pointer;
  margin: 5px;
  padding: 5px;
  background: #ccc;
  border-radius: 3px;
  width: 50px;
  margin-left: ${props => (props.userTap ? "100px" : "15px")};
  transition: all 0.2s ease-in;
`;

javascript css reactjs react-hooks css-in-js
1个回答
0
投票

[@ larz在注释中建议的唯一要做的就是将useState移动到最后一个组件,如下所示

© www.soinside.com 2019 - 2024. All rights reserved.