React ES6组件继承:工作,但不推荐
React ES6 component inheritance: working, but not recommended?
我目前以以下方式继承了ES6 React基础组件:
model.js (base component):
class ModelComponent extends React.Component {
render() {
// Re-used rendering function (in our case, using react-three's ReactTHREE.Mesh)
...
}
}
ModelComponent.propTypes = {
// Re-used propTypes
...
};
export default ModelComponent;
然后我有两个扩展组件,它们基本上都是这样的:
import ModelComponent from './model';
class RobotRetroComponent extends ModelComponent {
constructor(props) {
super(props);
this.displayName = 'Retro Robot';
// Load model here and set geometry & material
...
}
}
export default RobotRetroComponent;
(完整的源代码在这里)
这似乎可以正常工作。这两种型号都像我期望的那样出现和工作。
然而,我在多个地方读到继承不是React的正确方法-相反,我应该使用组合。但话又说回来,在React v0.13中不支持Mixins ?
那么,我上面采用的方法是可以的吗?如果没有,问题是什么,我应该如何做呢?
Facebook团队建议在编写React代码时"使用惯用的JavaScript概念",因为ES6类不支持mixin,所以应该只使用composition(因为你只是在使用惯用的JavaScript函数)。
在这种情况下,您可以使用composeModal
函数来接受组件并将其封装在高阶容器组件中返回。这个高阶组件将包含您希望传递给所有子组件的任何逻辑、状态和道具。
export default function composeModal(Component){
class Modal extends React.Component {
constructor(props){
super(props)
this.state = {/* inital state */}
}
render() {
// here you can pass down whatever you want 'inherited' by the child
return <Component {...this.props} {..this.state}/>
}
}
Modal.propTypes = {
// Re-used propTypes
...
};
return Modal
}
然后你可以像这样使用合成函数:
import composeModal from './composeModal';
class RobotRetroComponent extends React.Component {
constructor(props) {
super(props);
this.displayName = 'Retro Robot';
// Load model here and set geometry & material
...
}
render(){
return /* Your JSX here */
}
}
export default composeModal(RobotRetroComponent);
相关文章:
- Javascript:selenium Web驱动程序isDisplayed()不工作
- ES6构造函数返回基类的实例
- jQuery UI自动完成突然停止工作
- 如何在下面的ES6循环中获得前面的文本
- 双向绑定不会;我不在ES6工作
- 使用 Babel 将 ES6 模块转换为 ES5 AMD 模块,无法按预期工作
- ES6的解构赋值在最新的Node中不能工作
- ES6通过jspm错误在Firefox, Edge, Vivaldi,但工作在Chrome, Opera
- 通过ES6 Katas工作,扩展承诺
- React ES6类转换不工作
- 如何es6模块加载工作
- ES6下的webcomponents-lite在ie11和ie10下无法工作
- .call应该如何为ES6箭头函数工作(根据标准)
- 如何让ES6/2015导入/模块在浏览器中工作
- React组件不能在ES6上工作
- ES6导入和要求不能正常工作与gulp/browserify/babelify
- ES6中的导入/导出是如何工作的?
- es6如何让console.log在if语句中工作?
- 将 ES6 库转换回“工作”JavaScript
- React ES6组件继承:工作,但不推荐