正文
return React.Children.only(this.props.children)
}
}
ReactDocumentTitle.propTypes = {
title: PropTypes.string.isRequired
}
这份代码是将react-side-effect和react-document-title合并到一起做的事情,我把它叫做精简版。
使用该组件:
import ReactDocumentTitle from 'path/ReactDocumentTitle'
render() {
return (
//这里仅能有一个唯一的root元素。
)
}
如果你对高阶组件的写法有兴趣,可以研究一下react-side-effect。需要注意的是,这个高阶组件的代码是使用了babel编译后的结果,你可能看起来没那么容易理解。
如果把我上面写的那段代码使用babel编译,你再试着理解一下:
'use strict';
exports.__esModule = true;
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _propTypes = require('prop-types');
var _propTypes2 = _interopRequireDefault(_propTypes);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }