我想我的回答迟了。但我确实使用传统的基于原型的 javascript 对象制作了很多 React 组件。如果您喜欢基于原型的对象,可以尝试以下方法:)
一个简单的例子:
第一步:安装inherits模块
npm install inherits -S
那么,
const React = require('react'); // switch to import, if you like
const is = require('prop-types');
const inherits = require('inherits');
inherits(MyComponent, React.Component);
module.exports = MyComponent;
var prototype = MyComponent.prototype;
MyComponent.defaultProps = {
onClick: function(){ }
};
MyComponent.propTypes = {
onClick: is.func,
href: is.string,
label: is.string
}
function MyComponent(props) {
React.Component.call(this, props);
this.state = {clicked: false};
}
prototype.render = function() {
return (
<a href={this.props.href} onClick={this.props.onClick}>
{this.props.label}
</a>)
}
// for debugging purpose, set NODE_ENV production, will remove the following
if (process.env.NODE_ENV !== 'production') {
MyComponent.displayName = 'MyComponent';
}
分离关注点的更高级方法是将方法放在不同的文件中。 (通常,受保护的或私有的方法,几个月或几年后你就不需要知道了。)然后,将它们合并到原型对象中。您可以通过以下方式进行。
...
const _proto = require('./prototype'); //make a prototype folder, and merge all files' methods into one.
...
var prototype = Object.assign(MyComponent.prototype, _proto);
或者,你想让你的组件成为一个 EventEmitter,你可以像下面这样:
....
const _proto = require('./prototype');
const Emitter = require('component-emitter');
....
var prototype = Object.assign(MyComponent.prototype, _proto, Emitter.prototype);
function MyComponent(props) {
React.Component.call(this, props);
this.onClick = _=> this.emit("click");
}
prototype.render = function() {
return <a href={this.props.href} onClick={this.onClick}>{this.props.label}</a>
}
在prototype文件夹中,可以这样写:
index.js
Object.assign(exports, require('./styles.js').prototype)
styles.js
const prototype = exports.prototype = {};
prototype.prepareStyles = function() {
var styles = Object.defineProperties({}, {
wrapper: { get: _=> ({
backgroundColor: '#333'
})},
inner: {get: _=> {
return this.state.clicked ? {...} : {...}
}}
});
Object.defineProperties(this, {
styles: {get: _=> styles}
})
}
//All the methods are prefixed by prototype, so it is easy to cut and paste the methods around different files, when you want to hide some methods or move some methods to be with the constructor to make your component more easy to read.
然后,在主文件中。只需调用该方法即可准备所有样式:
function MyComponent(props) {
React.Component.call(this, props);
this.prepareStyles();
}
并使用样式,
prototype.render = function() {
return (
<div style={this.styles.wrapper}>
<div styles={this.styles.inner}>hello world</div>
</div>
)
}