我在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>
);
}
}
Run Code Online (Sandbox Code Playgroud)
当我单击按钮时,显示输入标签,但参考textInput仍设置为null。因此,我无法集中精力进行输入。
我发现了一些解决方法,例如:
autoFocus在输入标签中设置属性isEditing == false但这实际上是一个非常基本的模式,我想知道是否有一个干净的解决方案。
谢谢