触发状态变化的特定功能

Triggering specific function on state change

我正在尝试触发按钮在单击按钮时反弹,我正在尝试克服下面提到的一些问题:

  1. 如何停止 useSpring 仅在 click = true(也在加载时)时执行? 后续问题是。 true 是暂时的,我怎样才能做到这一点 它在动画完成后或 x 毫秒后恢复为 false。
  2. 每次输入中的 useState() 发生变化时,如何阻止它执行动画?
  3. 如何改善动画弹跳看起来更流畅? (可选)

export default function App() {
  const [click, setClick] = useState(false);
  const [input, setInput] = useState("");
  const clicked = useSpring({
    to: [{ transform: "scale(0.95)" }, { transform: "scale(1)" }],
    from: { transform: "scale(1)" },
    config: {
      mass: 1,
      tension: 1000,
      friction: 13
    }
  });

  const getInput = e => {
    setInput(e.target.value);
  };
  return (
    <div className="App">
      <Input placeholder="type here" onChange={getInput} />
      <animated.div style={clicked}>
        <Button style={{ width: "300px" }} onClick={() => setClick(true)}>
          Click me
        </Button>
      </animated.div>
    </div>
  );
}

我试过你的代码。我找到了一种方法。首先,您应该为 useSpring 添加一个条件,以便仅在点击为真时才播放动画。其次,您应该在动画完成后将 click 恢复为 false。我在此代码中的恢复部分使用了超时。

export default function App() {
  const [click, setClick] = useState(false);
  const [input, setInput] = useState("");
  const clicked = useSpring({
    to: click
      ? [{ transform: "scale(0.95)" }, { transform: "scale(1)" }]
      : [{ transform: "scale(1)" }],
    from: { transform: "scale(1)" },
    config: {
      mass: 1,
      tension: 1000,
      friction: 13
    }
  });

  const getInput = e => {
    setInput(e.target.value);
  };

  const handleClick = () => {
    setClick(true);
    setTimeout(() => setClick(false), 700);
  };

  return (
    <div className="App">
      <Input placeholder="type here" onChange={getInput} />
      <animated.div style={clicked}>
        <Button style={{ width: "300px" }} onClick={handleClick}>
          Click me
        </Button>
      </animated.div>
    </div>
  );
}

https://codesandbox.io/s/focused-joliot-lk68o