更改 final-form-focus 中聚焦元素的顺序

Change the order of the focused elements in final-form-focus

我使用 final-form-focusreact-final-form 来关注第一个错误,如果在提交时有任何验证错误。我有一个自定义的 react-select 组件,所以我使用的是自定义的 findInput 方法,如下所示:

const findInput = (inputs, errors) =>
  inputs.find(input => {
    const name = input.name || input.dataset.name;
    return name && getIn(errors, name);
  });

const getFormInputs = name => () => {
  if (typeof document === "undefined") {
    return [];
  }
  const form = document.forms[name];
  const inputs = form && form.length ? Array.prototype.slice.call(form) : []; // cast cheat to get from HTMLFormElement children to FocusableInput

  // So far this is just copy-pasted from final-form-focus.
  // It would return inputs here, but here is the magic:

  const selectFields = Array.prototype.slice.call(
    document.querySelectorAll("[data-select]")
  );

  const allInputs = inputs.concat(selectFields);

  return allInputs;
};

const focusOnError = focusDecorator(getFormInputs("pay-form"), findInput);

我的 select 组件包裹在 div 中并使用 ref 像这样聚焦:

const SelectInput = ({
  input,
  meta,
  initialValue,
  ...rest
}) => {
  const selectRef = React.createRef();

  const setFocus = () => {
    selectRef.current.focus();
  };
  return (
    <div>
      <div
        className="input-wrapper"
        tabIndex="0"
        data-select
        data-name={input.name}
        onFocus={setFocus}
      >
        <Select
          {...rest}
          ref={selectRef}
          onChange={value => input.onChange(value)}
          value={input.value}
          openMenuOnFocus={true}
        />
      </div>
    </div>
  );
};

但是 select 只集中在行尾,在所有其他组件之后。这是我的 codesandbox。有什么方法可以改变焦点元素在文档中出现的顺序吗?

看起来无法通过 React-Select 在 <input/> 上设置 name 属性,但您 可以 设置id 通过 innerId.