if else 根据条件自动对焦

autofocus in react based on condition if else

如何根据this.props.email是否存在自动对焦输入名称?

if(this.props.email){
    // would like to set autofocus for  <input value={email} name="userName">    
}else{
   // would like to set autofocus for  <input name="password" />
}

 <input value={email} name="userName">             
 <input name="password" />

我正在考虑使用 refs 但想知道是否有更好的方法来访问输入的名称

你可以只使用 autofocus:

<input value={email} name="userName" autofocus={!!this.props.email} >             
<input name="password" autofocus={!this.props.email} />

或者,参考:

if(this.props.email){
    // would like to set autofocus for  <input value={email} name="userName">  
    this.emailInput.focus()  
}else{
    // would like to set autofocus for  <input name="password" />
    this.passwordInput.focus()
}

 <input value={email} name="userName" ref={input => {this.emailInput = input}}>             
 <input name="password" ref={input => {this.passwordInput = input}} />

你可能想试试这个

<input value={email} autoFocus={this.props.email} name="userName"> 

检查这个 Sandbox

这不使用 if-else,而是使用 this.props.email,如您的问题:

How to autofocus for input name based on whether this.props.email exists or not?


内部 Input.js(组件)

<input
  value={this.props.email}
  name="userName"
  autoFocus={this.props.email}
/>
<input name="password" autoFocus={!this.props.email} />

内部 index.js(父级)

<Input email={""} />