如何正确创建输入HOC组件?

时间:2017-06-22 08:04:01

标签: reactjs

我想创建一个累积字符数的组件

import React, {Component, PropTypes} from "react";

export const withAccumulate = (WrappedComponent) => {
    return class ControlCharsInput extends Component {

        static propTypes = {
            accumulate: PropTypes.number,
            afterAccumulate: PropTypes.func.isRequired
        };

        static defaultProps = {
            accumulate: 0
        };

        constructor(props) {
            super(props);
        }

        onInputChange = (e) => {
            const value = e.target.value;
            if(value.length > 0 && value.length < this.props.accumulate){
                e.preventDefault();
                return;
            }
            this.props.afterAccumulate(value);
        };

        render() {
            return <WrappedComponent onChange={this.onInputChange}/>;
        }
    };
};

但是永远不会调用onChange方法 我的错是什么? 使用

const SomeInput = props => (<input className=.../>)
const InputAccumulate = withAccumulate(SomeInput);

我还认为如果你摆脱HOC并制作一个简单的包装器组件。 但后来我将道具传递给包装器中的输入和道具并获得警告

render () {     // here props combined with afterAccumulate etc
 return (<input {...props} onChange={this.onChange}>)
}

1 个答案:

答案 0 :(得分:1)

您忘记将道具传递给SomeInput组件中的实际输入:

const SomeInput = (props) => (<input {...props}/>)

这是您固定的component