React Composition vs Inheritance

时间:2017-01-13 11:49:08

标签: reactjs

所以我在整个地方进行了继承与作文的讨论。我会谈谈我的用例。

我正在使用react创建组件层次结构。像按钮一样的东西 - > buttonBar例如。因此,对于这些事情,我在按钮组件中定义的任何功能都需要存在于buttonBar组件中。

class Button extends React.Component {
    shouldComponentUpdate()  {
        //do some prevalidation
        return result;
    }

    myButtonfn = () => {
        //do Something here
    }

    myButtonfn2 = () => {
        //doSomething else
    }
}

class ButtonBar extends Button {
    shouldComponentUpdate() {
        return myLogic && super.shouldComponentUpdate.call(this);
    }

    myButtonBarfn = () => {
        //I should be able to do this
        this.myButtonfn();
        this.myButtonfn2();
    }
}

目前我已经实现了继承来实现这一目标。解决这个问题的正确方法是什么?我不想回到es5的使用方式。 React.createClass。

我对组件中函数的使用。

class Button extends React.Component {
    shouldComponentUpdate()  {
        //do some prevalidation
        return result;
    }

    myButtonfn = () => {
        //do Something here
    }

    myButtonfn2 = () => {
        //doSomething else
    }
}

class ButtonBar extends React.Component {
    doSomething = () => {
        this.refs.abcd.myButtonfn();//To be able to do this, HOC doesn't work
    }
    render = () => {
        return (<Button ref="abcd"/>);
    }
}

2 个答案:

答案 0 :(得分:0)

编辑: 所以你刚刚编辑了你的答案,看起来就像我的答案。这应该是当前使用它的方式。

如果您可以使用es6,那么您可以创建一个名为button的类,您的buttonBar可以扩展按钮以具有按钮的所有功能。

像这样:

git fetch origin pull/36/head
git log FETCH_HEAD

答案 1 :(得分:0)

page.driver.browser.action.move_to(page.find('YourElement').native).perform