跟进 Egghead.io 的视频 - “ES 6 类中的 React 组件”,以下内容有效:
'use strict';
import React from 'react';
import Button from './components/form/button';
import Label from './components/form/label';
<小时/>
// after refactoring
//import ReactMixin from './super-classes/react-mixin';
//ToDo:下面的 react 器
let reactMixin = InnerComponent => class extends React.Component {
constructor() {
super()
this.state = {count: 0}
//binding custom methods
this.increment = this.increment.bind(this);
}
increment() {
this.setState({count: this.state.count + 1});
}
render() {
return (
<InnerComponent update={this.increment} {...this.state} {...this.props} />
)
}
}
<小时/>
let ButtonMixed = reactMixin(Button); // using local variable
let LabelMixed = reactMixin(Label); // using local variable
class App extends React.Component {
render(){
return(<section>
// WOULD LIKE TO DO
// <ReactMixin component={?Button?} />
// <ReactMixin component={?Label?} />
<LabelMixed txt="I am a mixed label calling a form component" />
<ButtonMixed txt="I am a mixed button, me too! " />
</section>);
}
}
App.propTypes = {txt: React.PropTypes.any};
module.exports = App;
问题:
我正在尝试将 ReactMixins 重构为一个单独的组件,然后将其导入, 然后在我的渲染中使用它,如下所示:
<ReactMixins component={?} />
关于如何最好地重构它以供多种使用的任何想法?
谢谢...
最佳答案
更新:在对 ES6 React 组件进行了更多研究之后,我更倾向于组合方法,但我将在这里留下我的答案供后代使用。
Mixin 即将被淘汰,取而代之的是组合或继承。
如果我正确理解您的情况,最简单的事情就是创建一个您继承的“基础”组件。像这样的东西:
export default class BaseButton extends React.Component {
constructor(){
super();
//Set default state... if you want to
}
componentWillMount() {
console.log("I will run anytime someone extends baseButton");
}
//etc
}
所有按钮逻辑都在哪里,那么您可以像这样扩展它
然后:
export default class MyButton extends BaseButton {
//I will already have the things that BaseButton has
}
现在您已经通过 super()
或 this.whatever()
获得了您想要的一切。
如果您喜欢组合方法,我建议您阅读以下内容:
https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750
关于ReactJs - 在 ES6 中使用 Mixins,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30881392/