我正在嘗試製作一個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 };
謝謝!
P粉9905682832024-04-02 00:10:18
我相信,將src狀態放在父組件中,透過將setSrc作為prop傳遞給該組件,而不是在此組件中聲明src狀態,將有助於您。所以在這個元件中,onChange={() => setSrc(newVal)}
,其中setSrc作為prop傳遞給了Select元件。
或者,我建議將evt.target.value儲存為狀態,並在onChange事件中更新該值。
const [chosenImg, setChosenImg] = useState() const [src, setSrc] = useState(require("../data/sprites/bulbasaur.png")); useEffect(() => { setSrc(require(`../data/sprites/${chosenImg}.png`)) }, [chosenImg]);
然後:
onChange={()=> setChosenImg(evt.target.value)}