写了一个React的HOC出了点问题

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 />)
阅读 4.5k
1 个回答

传进去的<Input />React Element而非class,因此调用处直接写HOC(Input)即可

第二个问题,你在HOC中获取的是class而不是React Element,而组件数据是相对React Element而言的,因此答案是无法获取

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题