HOC功能:
接受antd
组件中的Input | TextArea
等输入组件,将 lodash
中的 debounce
方法注入到 onchange
事件当中。
代码如下:
import React, {Component} from 'react';
import {debounce} from 'lodash';
export default (WrapperComponent) => {
// WrapperComponent 就是传入的 `Input` | `TextArea` 组件
return class extends Component {
constructor() {
super(...arguments);
this.state = {
value: null
}
}
// input onChange 方法
changeHandler = (e) => {
e.persist();
this.delayChange(e.target.value.trim());
}
//
componentWillMount() {
this.delayChange = debounce((v) => {
this.setState({value: v});
}, 300);
}
render () {
const {value} = this.state;
if(!value) return null;
return <WrapperComponent
defaultValue={value ? value : null}
onChange={this.changeHandler}
onBlur={this.saveInputValue}
/>;
}
};
};
在调用的时候报warning
了,如下:Warning: Functions are not valid as a React child. This may happen if you return a Component instead of <Component /> from render. Or maybe you meant to call this function rather than return it.
还有一个问题是:怎么能把 WrapperComponent
组件上的数据,拿到当前的高阶组件内部?
补充:
高阶组件调用:
import {Input} from 'antd';
HOC(<Input />)
传进去的
<Input />
是React Element
而非class
,因此调用处直接写HOC(Input)
即可第二个问题,你在HOC中获取的是
class
而不是React Element
,而组件数据是相对React Element
而言的,因此答案是无法获取