[英]How to focus input when a user clicked on an input?
我嘗試在 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
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>
</>
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.