Reactjs 如何在钩子上扩展React功能组件?
我知道这不是推荐的方法,但无论如何,我很好奇如何通过功能组件和挂钩来实现。考虑以下例子:Reactjs 如何在钩子上扩展React功能组件?,reactjs,class,user-interface,inheritance,react-hooks,Reactjs,Class,User Interface,Inheritance,React Hooks,我知道这不是推荐的方法,但无论如何,我很好奇如何通过功能组件和挂钩来实现。考虑以下例子: class SimpleComponent extends Component { method1 = () => { console.log('Method 1'); }; method2 = () => { console.log('Method 2'); }; renderMessage2() {
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>
);
}
}
类SimpleComponent扩展组件{
方法1=()=>{
console.log(“方法1”);
};
方法2=()=>{
console.log(“方法2”);
};
renderMessage2(){
返回(
信息2
);
}
render(){
返回(
信息1
{this.renderMessage2()}
);
}
}
类EnhancedComponent扩展了SimpleComponent{
方法1=()=>{
console.log(“增强的方法1”);
};
方法2=()=>{
console.log(“增强的方法2”);
};
renderMessage2(){
返回(
增强信息2
);
}
}
我们如何通过功能组件和挂钩实现这种行为 实际上我不喜欢这样,但我认为我们可以这样做:
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'); }}
/>
);
}
函数消息2({method2Function}){
返回(
信息2
);
}
函数method1(){
console.log(“方法1”);
}
函数方法2(){
console.log(“方法2”);
}
函数SimpleComponent({Message2Component=Message2,method1Function=method1,method2Function=method2}){
返回(
信息1
);
}
函数增强消息2({method2Function}){
返回(
增强信息2
);
}
函数增强组件(){
返回(
{console.log('Enhanced Method 1');}
method2Function={()=>{console.log('Enhanced Method 2');}
/>
);
}
所以你问了一个关于做一些不被推荐的事情的问题,并用一种你不喜欢的方法回答了自己?我不明白这有什么用。继承通常是个坏主意。@Brianthonpson我只是想了解也许还有另一种更优雅的方法可以做到这一点。@JMadelaine如果我们想提供定制组件的可能性,我们该怎么办?道具组件看起来很凌乱,尤其是当我们不知道哪些组件可以被覆盖,哪些组件不能被覆盖时。请将您的组件包装到另一个组件中。看看装饰图案。