Skip to content

Instantly share code, notes, and snippets.

@monkindey
Last active August 16, 2017 02:39
Show Gist options
  • Save monkindey/a7d789b0de83a450daa8ddcabc181f4d to your computer and use it in GitHub Desktop.
Save monkindey/a7d789b0de83a450daa8ddcabc181f4d to your computer and use it in GitHub Desktop.
React higher-order component
import React, { Component, cloneElement } from 'react';
import ReactDOM from 'react-dom';
const injectRender = Decorated => {
class Inject extends Decorated {
render() {
const renderElement = super.render();
const children = React.Children
.map(renderElement.props.children, child => {
if (typeof child === 'string') {
return child;
} else {
return cloneElement(child);
}
})
.concat('inject children');
return cloneElement(renderElement, {}, children);
}
}
return Inject;
};
class ClassDemo extends Component {
render() {
const props = this.props;
return (
<div>
{props.content ? props.content : '我是一个普通组件'}
{props.children}
</div>
);
}
}
ReactDOM.render(
<InjectDemo>
<div>Test Of Class</div>
</InjectDemo>,
document.getElementById('app')
);
import React, { Component, cloneElement } from 'react';
import ReactDOM from 'react-dom';
// 就像vue的filter
const reverse = str => str.split('').reverse().join('');
const withHeader = Decorated => props => {
const { title, ...rest } = props;
return (
<div>
<h3>
{title ? title : '我是标题'}
</h3>
<Decorated {...rest} />
</div>
);
};
const Demo = props =>
<div>
{props.content ? props.content : '我是一个普通组件'}
{props.children}
</div>;
const EnhanceDemo = withHeader(Demo);
ReactDOM.render(
<EnhanceDemo title="高阶组件" content={reverse('我是一个普通组件')}>
<div>Test</div>
</EnhanceDemo>,
document.getElementById('app')
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment