高度なコンポーネントパターン
高階コンポーネントの概念
import React from 'react';
const EnhancedComponent = higherOrderComponent(BaseComponent);
class BaseComponent extends React.PureComponent {
render() {
return <div>名前:{this.props.name}</div>;
}
}
function higherOrderComponent(WrappedComponent) {
return class Enhanced extends React.PureComponent {
render() {
return <WrappedComponent {...this.props}/>;
}
};
}
export default EnhancedComponent;
propsの拡張
function enhanceWithProps(WrappedComponent) {
return props => <WrappedComponent {...props} additionalProp="追加データ"/>;
}
認証機能の実装
function withAuthentication(WrappedComponent) {
return class AuthWrapper extends React.PureComponent {
render() {
return this.props.isAuthenticated
? <WrappedComponent {...this.props}/>
: <LoginComponent/>;
}
};
}
ライフサイクルの計測
function withPerformanceMetrics(WrappedComponent) {
return class PerformanceWrapper extends React.PureComponent {
componentDidMount() {
console.log(`${WrappedComponent.name} のレンダリング時間: ${this.renderTime}ms`);
}
render() {
return <WrappedComponent {...this.props}/>;
}
};
}
refの転送
const CustomComponent = React.forwardRef((props, ref) => (
<div ref={ref}>カスタムコンポーネント</div>
));
Portalの使用
class Modal extends React.PureComponent {
render() {
const container = document.createElement('div');
document.body.appendChild(container);
return ReactDOM.createPortal(this.props.children, container);
}
}
コンポーネントの補完とスタイリング
Fragmentの利用
<>
<div>コンテンツ1</div>
<div>コンテンツ2</div>
</>
StrictModeによる開発支援
<React.StrictMode>
<AppComponent/>
</React.StrictMode>
CSS Modulesによるスタイリング
import styles from './Component.module.css';
const Component = () => (
<div className={styles.container}>
コンテンツ
</div>
);
Styled Componentsの活用
import styled from 'styled-components';
const StyledButton = styled.button`
background: ${props => props.primary ? 'blue' : 'white'};
color: ${props => props.primary ? 'white' : 'blue'};
`;
const ThemeButton = styled(StyledButton)`
font-size: 1.2em;
margin: 1em;
`;
テーマ機能の実装
const ThemeContext = React.createContext();
const ThemedComponent = styled.div`
color: ${props => props.theme.textColor};
background: ${props => props.theme.backgroundColor};
`;
<ThemeContext.Provider value={theme}>
<ThemedComponent/>
</ThemeContext.Provider>