react之高阶组件(一)
当两个或多个组件有相同的地方,可以将相同的部分抽离出来
先创建三个组件A、B、C
A.js
1 import React, { Component } from 'react' 2 3 class A extends Component { 4 render () { 5 return ( 6 <div> 7 A组件 8 </div> 9 ) 10 } 11 } 12 13 export default A
B.js
import React, { Component } from 'react' class B extends Component { render () { return ( <div> B组件 </div> ) } } export default B
C.js
import React, { Component } from 'react' class C extends Component { render () { return ( <div> C组件 </div> ) } } export default C
然后在app.js中引入
import React, { Component } from 'react'; import A from './components/A' import C from './components/C' import B from './components/B' class App extends Component { render() { return ( <div> <A /> <B /> <C /> </div> ); } } export default App;
认定A组件为相同部分,改写A组件
import React, { Component } from 'react' function A (WrappedComponent) { return class A extends Component { render () { return ( <div> <div>组件名称</div> <div> <WrappedComponent></WrappedComponent> </div> </div> ) } } } export default A
然后在B、C组件里面引用,改写B、C组件
import React, { Component } from 'react' import A from './A' class B extends Component { render () { return ( <div> B组件 </div> ) } } export default A( B )
import React, { Component } from 'react' import A from './A' class C extends Component { render () { return ( <div> C组件 </div> ) } } export default A( C )