掌握 React 中的 SOLID 原则:简单示例和最佳实践
单一职责原则(SRP)
一个组件应该只有一个改变的原因,这意味着它应该只有一项工作。
示例:用户配置文件组件
做:
- 将职责分解为更小的功能组件。
// UserProfile.js
const UserProfile = ({ user }) => {
return (
<div>
<UserAvatar user={user} />
<UserInfo user={user} />
</div>
);
};
// UserAvatar.js
const UserAvatar = ({ user }) => {
return <img src={user.avatarUrl} alt={`${user.name}'s avatar`} />;
};
// UserInfo.js
const UserInfo = ({ user }) => {
return (
<div>
<h1>{user.name}</h1>
<p>{user.bio}</p>
</div>
);
};
不:
- 将显示、数据获取和业务逻辑结合在一个组件中。
// IncorrectUserProfile.js
const IncorrectUserProfile = ({ user }) => {
// Fetching data, handling business logic and displaying all in one
const handleEdit = () => {
console.log("Edit user");
};
return (
<div>
<img src={user.avatarUrl} alt={`${user.name}'s avatar`} />
<h1>{user.name}</h1>
<p>{user.bio}</p>
<button onClick={handleEdit}>Edit User</button>
</div>
);
};
开放/封闭原则(OCP)
软件实体应该对扩展开放,但对修改关闭。
示例:主题按钮
做:
- 使用 props 来扩展组件功能,而无需修改原始组件。
// Button.js
const Button = ({ onClick, children, style }) => {
return (
<button onClick={onClick} style={style}>
{children}
</button>
);
};
// Usage
const PrimaryButton = (props) => {
const primaryStyle = { backgroundColor: 'blue', color: 'white' };
return <Button {...props} style={primaryStyle} />;
};
不:
- 修改原有的组件代码,直接添加新的样式或者行为。
// IncorrectButton.js
// Modifying the original Button component directly for a specific style
const Button = ({ onClick, children, primary }) => {
const style = primary ? { backgroundColor: 'blue', color: 'white' } : null;
return (
<button onClick={onClick} style={style}>
{children}
</button>
);
};
里氏替换原则(LSP)
超类的对象应该可以用其子类的对象替换,而不会破坏应用程序。
示例:基本按钮和图标按钮
做:
- 确保子类组件可以无缝替换超类组件。
// BasicButton.js
const BasicButton = ({ onClick, children }) => {
return <button onClick={onClick}>{children}</button>;
};
// IconButton.js
const IconButton = ({ onClick, icon, children }) => {
return (
<button onClick={onClick}>
<img src={icon} alt="icon" />
{children}
</button>
);
};
不:
- 引入替换时会破坏功能的子类特定属性。
// IncorrectIconButton.js
// This button expects an icon and does not handle the absence of one, breaking when used as a BasicButton
const IncorrectIconButton = ({ onClick, icon }) => {
if (!icon) {
throw new Error("Icon is required");
}
return (
<button onClick={onClick}>
<img src={icon} alt="icon" />
</button>
);
};
接口隔离原则(ISP)
任何客户端都不应被迫依赖其不使用的方法。
示例:文本组件
做:
- 针对不同的用途提供特定的接口。
// Text.js
const Text = ({ type, children }) => {
switch (type) {
case 'header':
return <h1>{children}</h1>;
case 'title':
return <h2>{children}</h2>;
default:
return <p>{children}</p>;
}
};
不:
- 用不必要的属性使组件变得混乱。
// IncorrectText.js
// This component expects multiple unrelated props, cluttering the interface
const IncorrectText = ({ type, children, onClick, isLoggedIn }) => {
if (isLoggedIn && onClick) {
return <a href="#" onClick={onClick}>{children}</a>;
}
return type === 'header' ? <h1>{children}</h1> : <p>{children}</p>;
};
依赖倒置原则(DIP)
高级模块不应该依赖于低级模块。两者都应该依赖于抽象。
示例:数据获取
做:
- 使用钩子或类似模式来抽象数据获取
和国家管理。
// useUserData.js (Abstraction)
const useUserData = (userId) => {
const [user, setUser] = useState(null);
useEffect(() => {
fetchData(userId).then(setUser);
}, [userId]);
return user;
};
// UserProfile.js
const UserProfile = ({ userId }) => {
const user = useUserData(userId);
if (!user) return <p>Loading...</p>;
return <div><h1>{user.name}</h1></div>;
};
不:
- 在组件内部进行硬编码数据提取。
// IncorrectUserProfile.js
const IncorrectUserProfile = ({ userId }) => {
const [user, setUser] = useState(null);
useEffect(() => {
// Fetching data directly inside the component
fetch(`https://api.example.com/users/${userId}`)
.then(response => response.json())
.then(setUser);
}, [userId]);
if (!user) return <p>Loading...</p>;
return <div><h1>{user.name}</h1></div>;
};