首页 文章

如何扩展通过React.createClass创建的React组件类

提问于
浏览
3

我有一个由React.createClass方法创建的现有React组件 . 我想通过在ES6中使用类扩展功能来重用该React组件(用于方法覆盖目的),但结果是意外的 . 例:

//an existing React component created via React.createClass
var ab = React.createClass({
    say(){
        console.log('ab class')
    },
    render(){
        return null;
    }
});

class c1 extends ab {
    say(){
        console.log('c1 class')
    };
}

o = new c1();
console.log(o.say()); //The expected console output is "c1 class" 
                      //but its showing "ab class"

1 回答

  • 4

    React类与ES6类不同 - 前者特定于React,后者只是标准的JavaScript构造 . 正如LukeMcGregor所说,你无法使用ES6扩展旧样式组件,至少不能使用ES6扩展语法 . 你唯一的选择可能是将ab更新为ES6类,如果你想像这样扩展它:

    import React from "react";
    
    class ab extends React.Component {
        say() {
            console.log('ab class')
        }
    
        render() {
            return null;
        }
    }
    
    class c1 extends ab {
        say() {
            console.log('c1 class')
        }
    }
    

    使用ES6类而不是React类时需要考虑一些注意事项,即缺少后者提供的自动绑定功能 . 可以在此处找到更多信息以及解决方法:http://www.ian-thomas.net/autobinding-react-and-es6-classes/ .

    EDIT: 好的,看到你可以't edit the original class, here'另一个想法(老实说,它是's probably a better idea than extending an existing component). A common concept in React is that of '组成' - this is where you create a component that wraps around an existing one. A component created in this way is often referred to as a '更高阶的组件';在你的情况下,它可能看起来像这样:

    import React from "react";
    
    var ab = React.createClass({
        say() {
            console.log('ab class')
        },
    
        render() {
            return (<div>I am the AB class</div>);
        }
    });
    
    class c1 extends React.Component {
        say() {
            console.log('c1 class')
        };
    
        render() {
            return (<ab />);
        }
    }
    

    这看起来似乎不是近似继承,但你实际上可以做很多事情 - 如果你想在你现有的组件和新组合的组件之间来回传递数据,你可以只使用 ab 组件上的道具(看作是你的第三方组件,我想它有一个非常好的API) . 如果需要从基类访问方法,you can use refs, as described in this answer .

    组合是一个非常强大的模式 - 我在我的应用程序中使用它的主要方法之一是为UI创建完全无状态的组件,然后创建包裹并将它们连接到所需数据的'container'组件 . 这在UI和逻辑之间创建了一个非常好的分离(Dan Abramov wrote about the concept here - he's about 10000x smarter than I am and I'd be terrible at React without some of the stuff he's posted) .

相关问题