
s:单一职责 - 一只神奇宝贝,一份工作
问题:pokemoncomponent 处理捕捉、战斗和显示分数,违反了 srp。
function pokemoncomponent({ pokemon, oncatch, onbattle, score }) {
return (
{pokemon.name}
score: {score}
);
}
解决方案:责任划分。
function pokemoncatcher({ pokemon, oncatch }) {
return ;
}
function pokemonbattler({ pokemon, onbattle }) {
return ;
}
function scoreboard({ score }) {
return score: {score};
}
function pokemongame({ pokemon, oncatch, onbattle, score }) {
return (
{pokemon.name}
);
}
o:开放/封闭 - 进化的神奇宝贝组件
问题:添加电源等功能需要修改现有组件。
解决方案:使用高阶组件(hoc)。
function withpowerup(pokemoncomponent) {
return function poweredupcomponent(props) {
const [ispoweredup, setpowerup] = usestate(false);
const powerup = () => {
setpowerup(true);
settimeout(() => setpowerup(false), 5000);
};
return (
);
};
}
const charmander = ({ ispoweredup }) => (
charmander {ispoweredup && "(powered up!)"}
);
const poweredcharmander = withpowerup(charmander);
function pokemonapp() {
return ;
}
l:里氏替换 - 可互换的神奇宝贝
问题:交换组件会导致问题。
解决方案:使用基础组件。
function basepokemon({ attack, children }) {
return (
attack: {attack}
{children}
);
}
function pikachu({ attack }) {
return (
pikachu
);
}
function charizard({ attack }) {
return (
charizard
);
}
function pokemonbattle() {
return (
generic pokémon
);
}
d:依赖倒置 - 依赖于抽象
问题:组件与数据源紧密耦合。
解决方案:使用上下文进行数据注入。
const PokemonContext = createContext();
function Pikachu() {
const { attack } = useContext(PokemonContext);
}
备忘单:坚实的原则
| 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. |










