Fix FormItem focus behavious, close #7351

This commit is contained in:
afc163 2017-09-01 14:13:09 +08:00
parent 1547b889b7
commit 668cec2f9e
2 changed files with 42 additions and 0 deletions

View File

@ -1,4 +1,5 @@
import React from 'react';
import { findDOMNode } from 'react-dom';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import PureRenderMixin from 'rc-util/lib/PureRenderMixin';
@ -212,6 +213,23 @@ export default class FormItem extends React.Component<FormItemProps, any> {
return false;
}
// Resolve duplicated ids bug between different forms
// https://github.com/ant-design/ant-design/issues/7351
onLabelClick = (e) => {
const id = this.props.id || this.getId();
if (!id) {
return;
}
const controls = document.querySelectorAll(`#${id}`);
if (controls.length !== 1) {
e.preventDefault();
const control = findDOMNode(this).querySelector(`#${id}`) as HTMLElement;
if (control && control.focus) {
control.focus();
}
}
}
renderLabel() {
const { prefixCls, label, labelCol, colon, id } = this.props;
const context = this.context;
@ -239,6 +257,7 @@ export default class FormItem extends React.Component<FormItemProps, any> {
htmlFor={id || this.getId()}
className={labelClassName}
title={typeof label === 'string' ? label : ''}
onClick={this.onLabelClick}
>
{labelChildren}
</label>

View File

@ -50,4 +50,27 @@ describe('Form', () => {
expect(wrapper.find('.ant-form-item-control-wrapper').length).toBe(2);
expect(wrapper.find('.ant-form-item-control-wrapper.ant-col-14').length).toBe(1);
});
// https://github.com/ant-design/ant-design/issues/7351
it('focus correct input when click label', () => {
const Form1 = Form.create()(({ form }) => (
<Form>
<Form.Item label="label 1">
{form.getFieldDecorator('test')(<input />)}
</Form.Item>
</Form>
));
const Form2 = Form.create()(({ form }) => (
<Form>
<Form.Item label="label 2">
{form.getFieldDecorator('test2')(<input />)}
</Form.Item>
</Form>
));
const wrapper = mount(<div><Form1 /><Form2 /></div>);
wrapper.find('Form label').at(0).simulate('click');
expect(wrapper.find('Form input').at(0).node).toBe(document.activeElement);
wrapper.find('Form label').at(1).simulate('click');
expect(wrapper.find('Form input').at(1).node).toBe(document.activeElement);
});
});