问题:PokemonComponent 处理捕捉、战斗和显示分数,违反了 SRP。
function PokemonComponent({ pokemon, onCatch, onBattle, score }) { return ( <div> <h2>{pokemon.name}</h2> <button onClick={() => onCatch(pokemon)}>Catch</button> <button onClick={() => onBattle(pokemon)}>Battle</button> <div>Score: {score}</div> </div> ); }
解决方案:责任划分。
function PokemonCatcher({ pokemon, onCatch }) { return <button onClick={() => onCatch(pokemon)}>Catch</button>; } function PokemonBattler({ pokemon, onBattle }) { return <button onClick={() => onBattle(pokemon)}>Battle</button>; } function ScoreBoard({ score }) { return <div>Score: {score}</div>; } function PokemonGame({ pokemon, onCatch, onBattle, score }) { return ( <div> <h2>{pokemon.name}</h2> <PokemonCatcher pokemon={pokemon} onCatch={onCatch} /> <PokemonBattler pokemon={pokemon} onBattle={onBattle} /> <ScoreBoard score={score} /> </div> ); }
问题:添加电源等功能需要修改现有组件。
解决方案:使用高阶组件(HOC)。
function withPowerUp(PokemonComponent) { return function PoweredUpComponent(props) { const [isPoweredUp, setPowerUp] = useState(false); const powerUp = () => { setPowerUp(true); setTimeout(() => setPowerUp(false), 5000); }; return ( <div> <PokemonComponent {...props} isPoweredUp={isPoweredUp} /> <button onClick={powerUp}>Power Up!</button> </div> ); }; } const Charmander = ({ isPoweredUp }) => ( <div>Charmander {isPoweredUp && "(Powered Up!)"}</div> ); const PoweredCharmander = withPowerUp(Charmander); function PokemonApp() { return <PoweredCharmander />; }
问题:交换组件会导致问题。
解决方案:使用基础组件。
function BasePokemon({ attack, children }) { return ( <div className="pokemon"> <div>Attack: {attack}</div> {children} </div> ); } function Pikachu({ attack }) { return ( <BasePokemon attack={attack}> <h2>Pikachu</h2> </BasePokemon> ); } function Charizard({ attack }) { return ( <BasePokemon attack={attack}> <h2>Charizard</h2> </BasePokemon> ); } function PokemonBattle() { return ( <div> <BasePokemon attack="Tackle"> <h2>Generic Pokémon</h2> </BasePokemon> <Pikachu attack="Thunderbolt" /> <Charizard attack="Flamethrower" /> </div> ); }
问题:组件与数据源紧密耦合。
解决方案:使用上下文进行数据注入。
const PokemonContext = createContext(); function Pikachu() { const { attack } = useContext(PokemonContext); } <PokemonContext.Provider value={{ attack: "Thunderbolt" }}> <Pikachu /> </PokemonContext.Provider>
Principle | Poké-Mantra | Trainer’s Tip |
---|---|---|
Single Responsibility | One Pokémon, one role. | Split complex components into focused ones. |
Open/Closed | Evolve without changing. | Use HOCs, render props for new features. |
Liskov Substitution | Components like Pokémon moves - interchangeable. | Ensure components can be used interchangeably. |
Dependency Inversion | Depend on abstractions, not concretes. | Use context or props for data management. |
以上是在 React 中构建一款可靠的 Pokémon 游戏:开发者的冒险!的详细内容。更多信息请关注PHP中文网其他相关文章!