简单教程
提交运行
代码编辑器:
<!doctype html> <meta charset="utf-8"> <title>React High Order Components -简单教程</title> <script src="https://cdn.staticfile.org/react/15.5.4/react.min.js"></script> <script src="https://cdn.staticfile.org/react/15.5.4/react-dom.min.js"></script> <script src="https://cdn.staticfile.org/babel-standalone/6.24.0/babel.min.js"></script> <div id="root"></div> <script type="text/babel"> var newData = { data: '从 Hoc 里传出来的数据...', } var MyHOC = ComposedComponent => class extends React.Component { componentDidMount() { this.setState({ data: newData.data }); } render() { return <ComposedComponent {...this.props} {...this.state} />; } }; class MyComponent extends React.Component { render() { return ( <div> <h1>{this.props.data}</h1> </div> ) } } var App = MyHOC(MyComponent); ReactDOM.render(<App/>, document.getElementById('root')); </script>
运行结果: