React的初学者,我遇到了一个问题 . 我有一个 Profiles 页面,用户可以在其中更改每个字段(名字,电子邮件等),按下“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 .
如何在现场删除阻塞/只读?
2 回答
我建议使用一个表单,因为它授予免费的
onEnter
功能,而不必连接一堆不同的事件处理程序 . 此外,我建议使用Controlled Components,它确实使用onChange
处理程序,但缓存组件状态中的所有输入值 . 这使得使用数据非常容易 .请参阅下面的代码示例
如何使用
value
而不使用onChange
在输入中写入内容?value={this.props.user.email}
没有onChange
这意味着您的输入是只读的https://jsfiddle.net/69z2wepo/84207/