2017-06-22 80 views
0

我要作出這樣的積累字符如何正確創建輸入HOC組件?

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

你已經忘了通過道具到實際的輸入您的SomeInput組件:

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

這裏是你的固定component