如何根据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,但想知道是否有更好的方法来访问输入的名称
答案 0 :(得分:1)
您可以只使用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}} />
答案 1 :(得分:1)
您可能想尝试一下
<input value={email} autoFocus={this.props.email} name="userName">
答案 2 :(得分:1)
这不使用 if-else ,而是使用 this.props.email ,如您的问题:
如何根据this.props.email是否存在来自动调整输入名称?
Input.js 内部(组件)
<input
value={this.props.email}
name="userName"
autoFocus={this.props.email}
/>
<input name="password" autoFocus={!this.props.email} />
在 index.js 内部(父级)
<Input email={""} />