我有一个redux-form集成的React组件(redux格式v7.0.1),当用户同时按下command
和enter
时,我试图触发提交。
我可以成功检查是否按下了两个键,但是我无法使用handleSubmit
通过表单外的函数提交表单。
如何将handleSubmit
用于我的onSubmit
功能?
方法:
constructor(props){
super(props);
this.state = {
commandKeyPressed: false
}
this.onSubmit = this.onSubmit.bind(this);
this.handleKeyDown = this.handleKeyDown.bind(this);
}
onSubmit(values){
console.log(values) // does not log anything
}
handleKeyDown(e){
if (e.keyCode === 91){
this.setState({commandKeyPressed: true});
}
// enter key is pressed afterwards while the keyCode is stored in a map to check if it was entered
if (e.key === 'Enter') {
e.preventDefault();
if (this.state.commandKeyPressed) {
//logs 'trying to submit', but does not call this.onSubmit
console.log('trying to submit',this.props.handleSubmit(this.onSubmit));
}
}
}
形式:
return (
<div>
<div className="ama-submit-field reply-container">
<form ref='commentReplyRef' onSubmit={handleSubmit(this.onSubmit)}>
<Field
name="commentReply"
keyDown={e => this.handleKeyDown(e)}
keyUp={e => this.handleKeyUp(e)}
type="input"
component={myCustomField}
label={text}>
</Field>
</form>
</div>
</div>
)
答案 0 :(得分:0)
好的,我发现了一个针对其他感兴趣的人的解决方法。我认为这是一个黑客,但它适用于我。
当我创建表单时
let CommentForm = reduxForm({
validate,
form: 'Comment',
onSubmit: function(values){return values}
})(Comment);
export default CommentForm
我使用onSubmit函数返回我的值。 我还更改了我的验证函数,以返回一个带有输入字段错误键的对象:
function validate(values){
const errors = {};
if (!values.commentReply){
errors.commentReply = {error:true, text:'Please enter a question.'}
}
return errors;
}
然后,在handleKeyDown
:
handleKeyDown(e){
if (e.keyCode === 91){
this.setState({commandKeyPressed: true});
}
// enter key is pressed afterwards while the keyCode is stored in a map to check if it was entered
if (e.key === 'Enter') {
e.preventDefault();
if (this.state.commandKeyPressed) {
var values = this.props.handleSubmit();
if (!values.commentReply.hasOwnProperty('error'){
this.onSubmit(values);
}
}
}
这允许我使用适当的值在我的react组件内触发我的提交函数。我认为更好的做法是将所有提交逻辑移动到reduxForm属性,但是我在React onSubmit函数中有很多特定于状态的行为,我只是选择将其保留在那里。