我似乎无法触发onSubmit
。任何人都可以发现这里的问题吗?我正在使用Ant Design,但我不认为这是问题。
注意:目前,下面的GraphQL突变(通过Apollo)确实已正确发送到了后端。在onClick
中删除Button
会触发onSubmit
,但是不会发送GraphQL查询。
更新:我没有找到解决方案,但是我发现如果删除此行if (loading) return <p>loading...</p>
,则会触发onSubmit
。
import React from 'react'
import gql from 'graphql-tag'
import { Mutation } from 'react-apollo'
import { Form, Input, Button, message } from 'antd'
import { __log } from '../utils/log.js'
const { TextArea } = Input
const ADD_MENTAL_MODEL_MUTATION = gql`
mutation AddMentalModel($mentalModelText: String!, $thoughts: [String!]){
addMentalModel(text: $mentalModelText, thoughts: $thoughts) {
text
id
}
}
`
class MentalModelForm extends React.Component {
// constructor(props){
// super(props)
// this.handleOnSubmit = this.handleOnSubmit.bind(this)
// }
handleOnSubmit = e => {
console.log('handleOnSubmit IS EXECUTED!!!!!')
e.preventDefault()
debugger
}
_hasErrors = (fieldsError) => {
return Object.keys(fieldsError).some(field => fieldsError[field])
}
render(){
const { getFieldDecorator, isFieldTouched, getFieldError, getFieldValue, getFieldsError } = this.props.form
return(
<Form onSubmit={ e => this.handleOnSubmit(e)}>
{/*
<Form onSubmit={this.handleOnSubmit}>
*/}
<Form.Item label='Mental Model'>
{
getFieldDecorator(
'mentalModel',
{
rules: [{required: false, whitespace: false, message: 'Missing or too short of a mental model'}]
}
)(<TextArea />)
}
</Form.Item>
<Form.Item label='Thought'>
{
getFieldDecorator(
'thought',
{
rules: [{required: false, whitespace: false, message: 'Must add a thought'}]
}
)(<Input />)
}
</Form.Item>
<Form.Item>
<Mutation
mutation={ADD_MENTAL_MODEL_MUTATION}
variables={
{
mentalModelText: getFieldValue('mentalModel'),
thoughts: [getFieldValue('thought')],
}
}
>
{
(mutation, {loading, error, data}) => {
if (loading) return <p>loading...</p>
return(
<Button
type='primary'
htmlType='submit'
onClick={mutation}
disabled={this._hasErrors(getFieldsError())}
>
Add new mental model
</Button>
)
}
}
</Mutation>
</Form.Item>
</Form>
)
} // render
} // class
export default Form.create({name: 'mentalmodel_hoc'})(MentalModelForm)
最佳答案
我认为Button
类型应该提交而不是主要的
<Button
type='submit'
onClick={mutation}
disabled={this._hasErrors(getFieldsError())}
>
Add new mental model
</Button>