2016-12-02 46 views
1

我有一個默認情況下禁用的輸入,但是當我調度一個動作來啓用它時,它應該變成能夠的。我也希望這個輸入變得有重點,但我無法做到這一點。這裏是我的組件:輸入不關注componentDidUpdate

class UserInput extends Component { 
    constructor (props) { 
     super(props); 

     this.state = { responseValue: '' }; 

     this.responseHandler = this.responseHandler.bind(this); 
     this.submitAnswer = this.submitAnswer.bind(this); 
    } 

    componentDidUpdate (prevProps) { 
     if (!this.props.disable && prevProps.disable) { 
      this.userInput.focus(); 
     } 
    } 

    responseHandler (e) { 
     this.setState({ responseValue: e.target.value }); 
    } 

    submitAnswer() { 
     this.props.submitUserAnswer(this.state.responseValue); 
     this.setState({ responseValue: '' }) 
    } 

    render() { 
     return (
      <div className="input-container"> 
       <input ref={(userInput) => { this.userInput = userInput; }} 
         className="input-main" 
         disabled={this.props.disable} 
         value={this.state.responseValue} 
         onChange={this.responseHandler} 
       /> 
       <button className="input-button" onClick={this.submitAnswer}>{this.props.strings.SEND}</button> 
      </div> 
     ); 
    } 
} 

UserInput.defaultProps = { 
    strings: { 
     'SEND': 'SEND', 
    }, 
}; 

UserInput.contextTypes = { 
    addSteps: React.PropTypes.func, 
}; 

export default Translate('UserInput')(UserInput); 

在此先感謝!

+0

http://stackoverflow.com/questions/6961526/correct-value-for-disabled-attribute –

回答

0

我落得這樣做,因爲我需要也是一個佔位符添加到殘疾人輸入:

class UserInput extends Component { 
    constructor (props) { 
     super(props); 

     this.state = { responseValue: '' }; 

     this.responseHandler = this.responseHandler.bind(this); 
     this.submitAnswer = this.submitAnswer.bind(this); 
    } 

    responseHandler (e) { 
     this.setState({ responseValue: e.target.value }); 
    } 

    submitAnswer() { 
     this.props.submitUserAnswer(this.state.responseValue); 
     this.setState({ responseValue: '' }) 
    } 

    render() { 
     return (
      <div className="input-container"> 
       { this.props.disable 
        ? <div className="disable-input-box">Wait to type your response</div> 
        : <input 
         className="input-main" 
         disabled={this.props.disable} 
         value={this.state.responseValue} 
         onChange={this.responseHandler} 
         autoFocus 
        /> 
       } 
       <button className="input-button" onClick={this.submitAnswer}>{this.props.strings.SEND}</button> 
      </div> 
     ); 
    } 
} 
0

我覺得你的問題就出在這裏:

if (!this.props.disable && prevProps.disable) { 
    this.userInput.focus(); 
} 

this.props.disable仍將是更新後的初始值(假)(它沒有被從我所看到的一個父組件更新),所以調用focus永遠不會被調用。