我在使用ref和条件渲染时遇到了问题。 我想在单击按钮标签时将焦点放在输入标签上。 基本上,我有这个简化的代码。
class App extends React.Component {
textInput
constructor(props) {
super(props)
this.state = {isEditing: false}
this.textInput = React.createRef()
}
onClick = () => {
this.setState({isEditing: !this.state.isEditing})
this.textInput.current.focus();
}
render () {
let edit = this.state.isEditing ?
(<input type="text" ref={this.textInput} />)
: ""
return (
<div>
<button onClick={this.onClick}>lorem </button>
{edit}
</div>
);
}
}
当我点击按钮时,输入标签会显示出来,但参考textInput
仍然设置为null
。因此,我无法聚焦输入。
我找到了一些解决方法,例如:
- 在输入标签中设置
autoFocus
属性 - 在
isEditing == false
时使用css隐藏输入标签
但实际上,这是一个非常基本的模式,我想知道是否有更简洁的解决方案。
谢谢
setState
的参数传递。 - huguesvincentsetState
的方式都不是这样。在我看来,API 应该 只 支持双函数形式,并且可能应该被称为setStateAsync
,但不幸的是现在为时已晚 :( - rossipediasetState()
,因为新状态取决于之前的状态。这也是官方文档推荐的方法。 - ChrissetState()
不是一个async
函数,不能使用await
等待。 - rossipedia