我正在尝试制作一个React应用程序,现在我有一个选择输入框,里面有一些宝可梦,我需要做的是每当选择改变(即宝可梦改变)时,宝可梦精灵会进行一个小的摇晃动画。目前我只有一个改变的精灵和一个在选择值改变时播放的音频。我该如何实现这个功能?我已经尝试使用
Select.ts
:
import { closest } from "fastest-levenshtein"; import React, { useState } from "react"; import { cries, pokemons } from "../data"; import styled from "styled-components"; import { Img, ani } from "../styles"; function Select() { const [src, setSrc] = useState(require("../data/sprites/bulbasaur.png")); const opts: { label: string; value: string }[] = []; for (let i = 0; i < pokemons.length; i++) { opts.push({ label: pokemons[i][0].toUpperCase() + pokemons[i].slice(1), value: pokemons[i], }); } return ( <div> <div> <select onChange={(evt) => { setSrc(require(`../data/sprites/${evt.target.value}.png`)); const str = closest(evt.target.value, cries); const res = new Audio(require(`../data/cries/${str}`)); res.volume = 0.2; res.play(); styled(Img)` margin-left: 2.5em; animation: ${ani}; `; }} > {opts.map(({ label, value }) => ( <option key={value} label={label} value={value}></option> ))} </select> </div> <Img src={src} alt="" className="sprite" /> </div> ); } export default Select;
img.styled.ts
:
import styled, { css } from "styled-components"; import { shake } from "./shake.stiled"; const ani = css(["", " 0.3s linear"] as any as TemplateStringsArray, shake); const Img = styled.img` margin-left: 2.5em; animation: ${ani}; `; export { Img, ani };
谢谢!
我相信,将src状态放在父组件中,通过将setSrc作为prop传递给该组件,而不是在此组件中声明src状态,将有助于您。所以在这个组件中,
onChange={() => setSrc(newVal)}
,其中setSrc作为prop传递给了Select组件。或者,我建议将evt.target.value存储为一个状态,并在onChange事件中更新该值。
然后: