我有一个默认禁用的输入,但是当我发送一个动作来启用它时,它应该能够。我也希望这些输入成为焦点,但我无法做到这一点。这是我的组成部分:
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 :(得分:0)
我认为你的问题在于:
DataContext
更新后 if (!this.props.disable && prevProps.disable) {
this.userInput.focus();
}
仍将是其初始值(false)(父组件未从我看到的内容更新)因此对this.props.disable
的调用永远不会调用。
答案 1 :(得分: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>
);
}
}