【发布时间】:2017-08-09 19:43:02
【问题描述】:
React 初学者,我遇到了一个问题。我有一个个人资料页面,用户可以在其中更改每个字段(名字、电子邮件等),一旦按下“Enter”,它就会保存该特定字段(redux/axios/promise)。
我遇到的问题是,当我使用 onKeyPress/Down/Up 作为事件触发器时,它会阻止任何数据输入。意思是,我不能在该字段中输入任何内容,就好像它是只读的或被阻止的一样。如果我使用 onChange,它可以工作。
class Account extends Component {
constructor( props ) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
if( e.key == 'Enter' ) { // this is detected (i console.logged it)
e.preventDefault(); // also tried without these
e.stopPropagation(); // also tried without these
// this is triggered but the text field doesn't change so it updates nothing
this.props.setUserKvPair( e.target.name, e.target.value );
}
}
render() {
return (
<div className="app-account row">
<div className="component-container col-12">
<div className="inner">
<p className="form-group">
<label className="form-text text-muted">Email Address</label>
<input
type="text"
name="email"
className="form-control"
value={this.props.user.email}
onKeyDown={this.handleChange} />
</p>
<p className="form-group">
<label className="form-text text-muted">First Name</label>
<input
type="text"
name="first_name"
className="form-control"
value={this.props.user.first_name}
onKeyPress={this.handleChange} />
</p>
</div>
</div>
</div>
);
}
}
const mapStateToProps = ( state ) => {
return {
user: state.user.data,
properties: state.properties.data,
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(userActions, dispatch);
}
export default connect( mapStateToProps, mapDispatchToProps )(Account);
基本上,一切正常,只是文本输入的值不会改变,除非我使用 onChange。
如何消除该字段上的阻塞/只读?
【问题讨论】:
-
也许您可以使用表单来执行此操作,然后挂钩
onSubmit事件并调用event.preventDefault()方法。然后您将免费获得按回车功能。此外,我通常建议使用受控组件进行输入。我将很快发布一个示例 sn-p 代码以符合我的建议。
标签: javascript reactjs redux