高阶组件
1.函数可以作为参数被传递
setTimeout(() => {
console.log(1)
}, 1000 );
2.函数可以作为返回值输出
function demo(x){
return function(){
return x;
}
}
//高阶函数的应用
//时间函数
setTimeout(function(){
console.info("Hello World");
},1000)
let i=0;
setInterval(function(){
console.info("Hello World");
})
//ajax
$.get("/api/getTime",function(){
console.info("获取成功");
})
//数组
some()、every()、filter()、map()和forEach();
使用高阶组件
1. higherOrderComponent(WrappedComponent) 普通写法
2. @ higherOrderComponent 装饰器
高阶组件应用
代理方式的高阶组件
返回的新组件类直接继承自React.Component类,新组件扮演的角色传入参数组件的一个代理,在新组件的render函数中,将被包裹组件渲染出来,除了高阶组件自己要做得工作,其余功能全部转手给了被包裹的组件
继承方式的高阶组件
采用继承关联行为参数的组件和返回的组件,假如传入的组件函数是WrappedComponent,那么返回的组件就直接继承自WrappedComponent
1.代理方式的高阶组件
1)操作prop (添加pros,删除props)
2)抽取状态
3)访问ref
4)包装组件
配置装饰器
高阶组件
import React, { Component } from 'react'
export default(title)=> WrappedComponent => class extends Component{
constructor(props){
super(props);
this.state={
value:""
}
}
// resc(instance){
// instance.getName&&alert("123456")
// }
onInputChange=(e)=>{
this.setState({
value:e.target.value
})
}
render() {
const {age,...otherProps}=this.props
const newProps={
value:this.state.value,
onInput:this.onInputChange
}
return (
<div className="a_container">
<div className="header">{title}
<div className="close">x</div>
</div>
<div>
{/* <WrappedComponent sex="男" {...otherProps} ref={this.resc.bind(this)}/> */}
<WrappedComponent sex="男" {...otherProps} {...newProps}/>
</div>
</div>
)
}
}
B组件
import React, { Component } from 'react'
import A from './../components/A';
class B extends Component {
constructor(props){
super(props);
console.info(props)
}
render() {
return (
<div >
{/* <input type="text" value={this.state.value} onInput={this.changeInput.bind(this)}/> */}
<input type="text" {...this.props}/><br/>
我的名字叫:{this.props.name}<br/>
我的年龄是:{this.props.age}<br/>
我的年龄是:{this.props.sex}<br/>
<img style={{width:'179px',height:'222px'}} src={require('./../images/u716.png')} alt=""/>
</div>
)
}
}
export default A("我是B组件")(B);
C组件
import React, { Component } from 'react'
import A from './../components/A';
class C extends Component {
constructor(props){
super(props);
}
getName(){
alert("我是组件C")
}
render() {
return (
<div >
<input type="text" {...this.props}/>
<img style={{width:'179px',height:'222px'}} src={require('./../images/person.png')} alt=""/>
</div>
)
}
}
export default A("我是C组件")(C);
D组件
import React, { Component } from 'react'
import A from './../components/A';
class D extends Component {
constructor(props){
super(props);
console.info('我是组件D')
}
render() {
return (
<div >
<img style={{width:'179px',height:'222px'}} src={require('./../images/u7023.png')} alt=""/>
</div>
)
}
}
export default A("我是D组件")(D);