Lưu ý: Bài đăng này đã được đăng tại thời điểm React KHÔNG hỗ trợ ES6 (v12).Thừa kế React và ES6
Tôi có một lớp ES6:
class BaseClass {
getInitialState(){
return {message: 'Hello!'};
}
render() {
return (
<div>
<div>{this.state.message}</div>
</div>
)
}
}
Rằng tôi có thể xuất khẩu trong ES6 sử dụng biểu thức này (nguồn: react ES6 browserify)
export default React.createClass(BaseClass.prototype)
này hoạt động tốt. Bây giờ tôi muốn sử dụng ES6 thừa kế để mở rộng BaseClass
lớp học của tôi:
class ExtendedClass extends BaseClass{
getInitialState(){
return {message: "Hello! I'm an extension"};
}
}
Nhưng khi tôi gọi React.createClass
trên lớp ExtendedClass
, tôi đã ngoại lệ sau đây:
Invariant Violation: ReactCompositeComponentInterface: You are attempting to define `constructor` on your component more than once. This conflict may be due to a mixin.
Tôi biết Phản ứng 0,13 được coi ES6 thân thiện hơn nhưng có cách nào để xử lý điều đó không?
EDIT:
Tôi đang sử dụng Traceur để biên dịch lớp ES6 tôi. Đầu ra cho ExtendedClass
trông giống như:
function ExtendedClass() {
"use strict";
if (BaseClass !== null) {
BaseClass.apply(this, arguments);
}
}
for (BaseClass____Key in BaseClass) {
if (BaseClass.hasOwnProperty(BaseClass____Key)) {
ExtendedClass[BaseClass____Key] = BaseClass[BaseClass____Key];
}
}
____SuperProtoOfBaseClass = BaseClass === null ? null : BaseClass.prototype;
ExtendedClass.prototype = Object.create(____SuperProtoOfBaseClass);
ExtendedClass.prototype.constructor = ExtendedClass;
ExtendedClass.__superConstructor__ = BaseClass;
ExtendedClass.prototype.getInitialState = function() {
"use strict";
return {message: "Hello! I'm an extension"};
};
React.createClass(ExtendedClass.prototype);
getInitialState không nên được sử dụng với mã es6. Thay vào đó, thiết lập trạng thái ban đầu của bạn trong hàm tạo, 'hàm tạo (đạo cụ) {super (đạo cụ); this.state = {message: 'Hello!'}} ' – widged
Bài đăng này đã được đăng tại thời điểm React KHÔNG hỗ trợ ES6 (v12). Nó không còn liên quan nữa. Tất nhiên với React v13 tất cả mọi thứ hoạt động tốt và không cần phải sử dụng workaround đề cập đến. – JBE