【问题标题】:How to focus input when a user clicked on an input?当用户点击输入时如何聚焦输入?
【发布时间】:2020-03-02 06:28:42
【问题描述】:
我尝试在 react.js 中创建一个搜索输入组件。在这个组件中,我希望当用户点击搜索图标时,输入焦点及其宽度由 css3 过渡属性增加。
这是我的一段代码:
<input className={"news-search-v2"} type="text" />
<i className="material-icons"> search </i>
还有我的组件的手写笔代码
.news-search-v2
width 0px
transition: ease 0.5s all
&:focus
border-bottom solid 1px #5f6368
width 300px
【问题讨论】:
标签:
javascript
html
css
reactjs
stylus
【解决方案1】:
向输入声明名称属性并将图标包装在标签元素中并为其提供“for”属性,其值将等于输入名称:Reason
<input name="search" className={"news-search-v2"} type="text" />
<label for="search"><i className="material-icons"> search </i></label>
让这个工作在反应。使用“htmlFor”而不是“for”:Reason
【解决方案2】:
Arnav Yagnik 答案是正确的,但不是React 解决方案。
如果你的组件是函数式的,你可以使用useRef钩子。
import React from 'react';
const FocusExample = () => {
const textInput = React.useRef(null);
const setFocus = React.useCallback(() => { textInput.current.focus() });
return (
<>
<input ref={textInput} className={"news-search-v2"} type="text" />
<i className="material-icons" onClick={setFocus}> search </i>
</>
);
};
或者,如果您使用基于分类的视图,请使用createRef:
import React from 'react';
class FocusExample extends React.Component {
constructor(props) {
super(props);
this.textInput = React.createRef();
}
setFocus = () => {
this.textInput.current.focus();
}
render() {
return(
<>
<input ref={this.textInput} className={"news-search-v2"} type="text" />
<i className="material-icons" onClick={this.setFocus}> search </i>
</>
);
}
}