我在语义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。我还尝试将Input包装在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();
}
}
知道我在这里缺少什么吗?
谢谢!
答案 0 :(得分:0)
这是解决方案,如此处所示: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 && 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>
)
}
}