#reactjs #typescript #semantic-ui-react
#reactjs #typescript #semantic-ui-react
Вопрос:
У меня есть простое всплывающее окно в Semantic UI React, которое содержит поле ввода. Это поле ввода должно быть сфокусировано сразу при открытии всплывающего окна. Пока безуспешно. Это то, что я пробовал:
import * as React from 'react';
import { Input, Label, Popup, Segment } from 'semantic-ui-react';
export class Test extends React.Component {
private searchInput: React.RefObject<Input>;
constructor(props: any) {
super(props);
this.searchInput = React.createRef();
}
public render() {
return (
<Popup
trigger={<Label>Test</Label>}
content={this.renderSelector()}
on="hover"
hoverable={true}
position="bottom left"
onOpen={() => this.focusInput()}
/>
)
}
private renderSelector() {
return (
<Segment>
<Input ref={this.searchInput} fluid={true} icon="search" iconPosition="left" />
</Segment>
)
}
private focusInput() {
if (this.searchInput.current) {
this.searchInput.current.focus()
}
}
}
this.searchInput.current
всегда равно null. Я также пытался обернуть ввод в Ref
компонент, но с тем же результатом:
private renderSelector() {
return (
<Segment>
<Ref innerRef={this.searchInput}>
<Input fluid={true} icon="search" iconPosition="left" />
</Ref>
</Segment>
)
}
Наконец, даже при попытке найти входные данные в DOM, я получаю нулевой результат:
private renderSelector() {
return (
<Segment>
<Input id="foobar" fluid={true} icon="search" iconPosition="left" />
</Segment>
)
}
private focusInput() {
const foo = document.getElementById("foobar");
if (foo) {
const bar = foo as HTMLInputElement;
bar.focus();
}
}
Есть идеи, чего мне здесь не хватает?
Спасибо!
Ответ №1:
Это решение, как указано здесь: https://github.com/Semantic-Org/Semantic-UI-React/issues/3473
Основная проблема в основном заключается в том, что ссылка доступна только на этапе фиксации (который включает метод componentDidUpdate).
import * as React from 'react';
import { Input, Label, Popup, Segment } from 'semantic-ui-react';
interface TestState {
isOpen: boolean;
}
export class Test extends React.Component<{}, TestState> {
private searchInput: React.RefObject<Input>;
constructor(props: any) {
super(props);
this.searchInput = React.createRef();
this.state = { isOpen: false };
}
public componentDidUpdate(prevProps: any, prevState: TestState) {
if (!prevState.isOpen amp;amp; this.state.isOpen) {
if (this.searchInput.current) {
this.searchInput.current.focus();
}
}
}
public render() {
return (
<Popup
trigger={<Label>Test</Label>}
content={this.renderSelector()}
on="hover"
hoverable={true}
position="bottom left"
onMount={() => this.setState({ isOpen: true })}
onUnmount={() => this.setState({ isOpen: false })}
/>
)
}
private renderSelector() {
return (
<Segment>
<Input ref={this.searchInput} fluid={true} icon="search" iconPosition="left" />
</Segment>
)
}
}