我知道这不是推荐的方法,但无论如何,我想知道如何通过功能组件和钩子来实现。考虑以下示例:
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>
);
}
}
我们如何使用功能组件和钩子来实现这样的行为?
实际上我不喜欢这样,但我认为我们可以这样做:
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'); }}
/>
);
}