In our daily projects, we often encounter that a new line of data, an input box or a drop-down box of this line of data can automatically obtain the focus, the same as editing; This problem may be difficult for some friends, here is a look at my implementation
To react, for instance
1. First, you need to obtain the DOM instance. That is, an actual instance of the input field or drop-down DOM element defines an firstInput,;
2. Specify a focusId and a focusId because there are multiple data items in the list
3. For a new row of data, assign the unique key value of the new data to the focusId and obtain the focus. After the focus is obtained, clear the focusId
this.focusId = id
focusInput(this.firstInput)
this.focusId = null
Copy the code
// Get focus when a row is added or changed
export function focusInput(input) {
setTimeout(() = > {
if (input && input.input && typeof input.input.focus === 'function') {
input.input.focus()
} else if (input && typeof input.focus === 'function') {
input.focus()
}
}, 0)}Copy the code
4. Get the DOM instance using the binding of the ref attribute input box or the dropdown box
<Select
ref={(node) = > record.id === this.focusId && (this.firstInput = node) }
{ feeItemList.map(item= ><Select.Option value={item} key={item}>{item }</Select.Option>)}
</Select> >
Copy the code