diff --git a/components/form/FormItem.tsx b/components/form/FormItem.tsx index e9517d842a..d2d2e8657e 100644 --- a/components/form/FormItem.tsx +++ b/components/form/FormItem.tsx @@ -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 { 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 { htmlFor={id || this.getId()} className={labelClassName} title={typeof label === 'string' ? label : ''} + onClick={this.onLabelClick} > {labelChildren} diff --git a/components/form/__tests__/label.test.js b/components/form/__tests__/label.test.js index 92fd9851d4..d999428b63 100644 --- a/components/form/__tests__/label.test.js +++ b/components/form/__tests__/label.test.js @@ -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.getFieldDecorator('test')()} + +
+ )); + const Form2 = Form.create()(({ form }) => ( +
+ + {form.getFieldDecorator('test2')()} + +
+ )); + const wrapper = mount(
); + 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); + }); });