Skip to content

Instantly share code, notes, and snippets.

@mvasilkov
Created June 25, 2019 08:41
Show Gist options
  • Save mvasilkov/e490c0ab8a450d5e6f14b91e87867fcf to your computer and use it in GitHub Desktop.
Save mvasilkov/e490c0ab8a450d5e6f14b91e87867fcf to your computer and use it in GitHub Desktop.
Ant.design modal form with wrappedComponentRef
import React from 'react'
import { Form, Input } from 'antd'
import lang from '../app/lang'
export default Form.create({ name: 'auth' })(
class AuthForm extends React.Component {
render() {
const { getFieldDecorator } = this.props.form
return (
<Form layout="vertical" onKeyPress={this.onKeyPress}>
<Form.Item label="Пассфраза">
{getFieldDecorator('passphrase', {
rules: [{ required: true, message: lang.requiredField }],
})(
<Input autoFocus />
)}
</Form.Item>
<Form.Item label="Соль">
{getFieldDecorator('salt')(
<Input />
)}
</Form.Item>
</Form>
)
}
onKeyPress = event => {
const { onEnterKeyPress } = this.props
if (event.key == 'Enter' && typeof onEnterKeyPress == 'function') {
onEnterKeyPress(event)
}
}
}
)
import React from 'react'
import { connect } from 'react-redux'
import { Modal } from 'antd'
import AuthForm from './auth_form'
import { authenticate } from '../reducers/auth'
import { closeAuth, waitAuth } from '../reducers/visual'
class AuthModal extends React.Component {
render() {
const { visible, waiting } = this.props
return (
<Modal onCancel={this.onCancel} onOk={this.onOk} title="Вход"
cancelText="Отменить" okText="Войти" className="auth-modal"
visible={visible} confirmLoading={waiting} closable={false}
destroyOnClose={true}>
<AuthForm wrappedComponentRef={ref => { this.wrapped = ref }}
onEnterKeyPress={this.onOk} />
</Modal>
)
}
onCancel = _ => {
const { closeAuth, waiting } = this.props
if (waiting) return
closeAuth()
}
onOk = _ => {
const { authenticate } = this.props
const { form } = this.wrapped.props
form.validateFields(async (err, fields) => {
if (err) return
const { passphrase, salt } = fields
await authenticate(passphrase, salt)
form.resetFields()
})
}
}
const stateToProps = state => state.visual.auth
const dispatchToProps = dispatch => ({
async authenticate(pwd, salt) {
dispatch(waitAuth())
await dispatch(authenticate(pwd, salt))
dispatch(closeAuth())
},
closeAuth() { dispatch(closeAuth()) },
})
export default connect(stateToProps, dispatchToProps)(AuthModal)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment