【发布时间】:2020-01-23 10:17:17
【问题描述】:
所以我想我的问题很简单,我希望当我单击一个元素时,我的输入获得焦点,所以这是我的组件上的方法和构造函数:
constructor(props) {
super(props);
this.textInput = React.createRef();
this.state = {
searchValue: ""
};
}
activateSearchZone = action => {
this.props.activateSearchZone(action);
console.log(this.textInput);
this.textInput.current.focus();
};
handleSearchZone = event => {
let searchValue = event.target.value;
this.props.searchForUsers(searchValue, { isSearching: true });
setTimeout(() => {
this.props.searchForUsers(searchValue, {
isSearching: false,
searchDone: true
});
}, 1000);
this.setState({
searchValue
});
};
这是我的组件:
{this.props.searchList.activated && (
<div className="search-bar__zone">
<FontAwesomeIcon icon={faSearch} size="xs"></FontAwesomeIcon>
<input
placeholder="Search"
onChange={event => this.handleSearchZone(event)}
value={this.state.searchValue}
type="text"
ref={this.textInput}
></input>
<FontAwesomeIcon
icon={faTimesCircle}
onClick={() => this.activateSearchZone(false)}
></FontAwesomeIcon>
</div>
)}
控制台日志显示当前值为null,我现在明白为什么了,我想是因为我的元素刚刚渲染,但我希望在单击时输入焦点。
我该怎么做?
非常感谢您的帮助。
【问题讨论】:
-
你试过
<input type="text" autoFocus>??。我认为这会自动聚焦输入字段 -
@AkhilAravind 我以前不知道这个,我在文档中寻找它,这就是我真正需要的,它有效,谢谢,如果你想写,我可以将你的答案标记为正确作为答案。
-
肯定会发布答案。
标签: reactjs