【发布时间】:2019-11-05 13:02:17
【问题描述】:
如果提交时出现任何验证错误,我将使用 final-form-focus 和 react-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);
我的选择组件被包裹在一个 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>
);
};
但是选择只集中在行尾,在所有其他组件之后。这是我的codesandbox。有什么方法可以改变焦点元素的顺序,就像它们出现在文档中一样?
【问题讨论】:
标签: reactjs react-select react-final-form