本文介绍了React ES6替代Mixins的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用ES6类时,我正在寻找React mixins的替代方法.

I'm looking for an alternative to React mixins when using ES6 classes.

我想向我的React组件中注入一些功能,但是这些功能需要React元素.

I would like to inject some functions into my react components, but those functions need React elements.

React ES5为此使用了混合器,但是React类不支持混合器.在React类中,mixin的替代方法是什么?

React ES5 used mixins for that, but React Classes don't support mixins. What's the alternative to mixins in React classes?

推荐答案

Mixins 以后不再受React支持.而不是它们,您应该使用高阶组件.此要点提供了对此概念的很好解释.

Mixins won't be supported by React in the future. Instead of them you should use Higher-order Components. This gist provides great explanation of this concept.

您应该创建一个单独的组件,以向其他组件提供此功能,而不是在组件中添加其他功能.

Instead of mixing extra functionality into your component you should create a separate one which will provide this functionality to another components.

class MyComponent extends React.component {
    render() {
        //...
    }
}

export default extraFunctionality(MyComponent);

如果您将Babel与ES7插件配合使用,则可以使用装饰器语法:

If you're using Babel with ES7 plugin you can use decorator syntax for that:

@extraFunctionality
class MyComponent extends React.component {
    render() {
        //...
    }
}

这篇关于React ES6替代Mixins的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 11:34