문제: 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: 개발자의 모험에서 견고한 포켓몬 게임 만들기!의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!