kys*_*nic 5 user-interface inheritance class reactjs react-hooks
我知道这不是推荐的方法,但无论如何我很好奇如何通过功能组件和挂钩来完成它。考虑以下示例:
class SimpleComponent extends Component {
method1 = () => {
console.log('Method 1');
};
method2 = () => {
console.log('Method 2');
};
renderMessage2() {
return (
<div onClick={this.method2}>Message 2</div>
);
}
render() {
return (
<div>
<div onClick={this.method1}>Message 1</div>
{this.renderMessage2()}
</div>
);
}
}
class EnhancedComponent extends SimpleComponent {
method1 = () => {
console.log('Enhanced Method 1');
};
method2 = () => {
console.log('Enhanced Method 2');
};
renderMessage2() {
return (
<div onClick={this.method2}>Enhanced Message 2</div>
);
}
}
Run Code Online (Sandbox Code Playgroud)
我们如何通过功能组件和钩子来实现这样的行为?
我实际上不喜欢这样,但我认为我们可以这样做:
function Message2({ method2Function }) {
return (
<div onClick={method2Function}>Message 2</div>
);
}
function method1() {
console.log('Method 1');
}
function method2() {
console.log('Method 2');
}
function SimpleComponent({ Message2Component = Message2, method1Function = method1, method2Function = method2 }) {
return (
<div>
<div onClick={method1Function}>Message 1</div>
<Message2Component method2Function={method2Function} />
</div>
);
}
function EnhancedMessage2({ method2Function }) {
return (
<div onClick={method2Function}>Enhanced Message 2</div>
);
}
function EnhancedComponent() {
return (
<SimpleComponent
Message2Component={EnhancedMessage2}
method1Function={() => { console.log('Enhanced Method 1'); }}
method2Function={() => { console.log('Enhanced Method 2'); }}
/>
);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
17261 次 |
| 最近记录: |