我有一个由 React.createClass 方法创建的现有 React 组件。我想通过使用 ES6 中的类扩展功能(用于方法覆盖目的)来重用该 React 组件,但结果出乎意料。示例:
//an existing React component created via React.createClass
var ab = React.createClass({
say(){
console.log('ab class')
},
render(){
return null;
}
});
class c1 extends ab {
say(){
console.log('c1 class')
};
}
o = new c1();
console.log(o.say()); //The expected console output is "c1 class"
//but its showing "ab class"
最佳答案
React 类与 ES6 类不同——前者是 React 特有的,后者只是一个标准的 JavaScript 构造。正如 LukeMcGregor 所说,您不能使用 ES6 扩展旧样式组件,至少不能使用 ES6 扩展语法。如果你想像这样扩展它,你唯一的选择可能是将 ab 更新为 ES6 类:
import React from "react";
class ab extends React.Component {
say() {
console.log('ab class')
}
render() {
return null;
}
}
class c1 extends ab {
say() {
console.log('c1 class')
}
}
在使用 ES6 类而不是 React 类时需要考虑一些注意事项,即缺少后者提供的自动绑定(bind)功能。可以在此处找到更多信息和解决方法:http://www.ian-thomas.net/autobinding-react-and-es6-classes/ .
编辑:好吧,鉴于您无法编辑原始类,这里有另一个想法(老实说,这可能比扩展现有组件更好)。 React 中的一个常见概念是“组合”——这是您创建一个组件来包裹现有组件的地方。以这种方式创建的组件通常被称为“高阶组件”;在您的情况下,它可能看起来像这样:
import React from "react";
var ab = React.createClass({
say() {
console.log('ab class')
},
render() {
return (<div>I am the AB class</div>);
}
});
class c1 extends React.Component {
say() {
console.log('c1 class')
};
render() {
return (<ab />);
}
}
这可能看起来不像继承,但实际上你可以用它做很多事情——如果你想在现有组件和新组合的组件之间来回传递数据,你可以只使用 props ab
组件(鉴于它是您的第 3 方组件,我想它有一个定义良好的 API)。如果您需要从基类访问方法,you can use refs, as described in this answer .
组合是一种非常强大的模式——我在我的应用程序中使用它的主要方式之一是为 UI 创建完全无状态的组件,然后创建“容器”组件,将它们环绕起来并将它们连接到它们需要的数据.这在 UI 和逻辑之间创建了一个非常好的分离(Dan Abramov wrote about the concept here - he's about 10000x smarter than I am and I'd be terrible at React without some of the stuff he's posted)。
关于javascript - 如何扩展通过 React.createClass 创建的 React 组件类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35909476/