我试图在 React 中使用 ES6 类,并希望所有组件都继承某些方法,但是一旦我尝试扩展扩展 React.Component 类的组件, componentDidMount 方法就不会触发,因此什么也不会发生被渲染。我正在使用的代码:
基础组件.jsx
import React from 'react';
class BaseComponent extends React.Component {
constructor() {
super();
console.log('BaseComponent constructor');
}
render() {
return (
<div>Hello, Im the base component</div>
);
}
}
export default BaseComponent;
示例组件.jsx
import BaseComponent from './BaseComponent';
class ExampleComponent extends BaseComponent {
constructor(props) {
super(props);
}
componentDidMount() {
console.log('exampleComponent mounted');
}
render() {
return (
<div>Hello, Im the example component</div>
);
}
}
export default ExampleComponent;
App.jsx
import React from 'react';
React.render(<ExampleComponent />, document.body);
我正在使用 React 0.13.3,并使用 babelify 6.1.2 进行转译。
字符串“exampleComponent Mounted”永远不会记录到控制台,并且不会呈现任何内容。有什么想法我做错了吗?
我不确定该方法,但这段代码也有效:
export default class Service extends BaseComponent {
componentDidMount(...args) {
super.componentDidMount.apply(this, args);
}
}
UPD:但这被认为是一种不好的做法:
a) https://medium.com/@dan_abramov/how-to-use-classes-and-sleep-at-night-9af8de78ccb4 https://medium.com/@dan_abramov/how-to-use-classes-and-sleep-at-night-9af8de78ccb4
b) https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750 https://medium.com/@dan_abramov/mixins-are-dead-long-live-higher-order-components-94a0d2f9e750
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)