Эй, вы не можете использовать хуки в компоненте класса, они предназначены для использования в функциональном компоненте в компонентах класса, вы можете вместо этого просто использовать state
и this.setState
, поэтому для вашего кода версия класса будет:
class CustomTextInput extends React.Component {
textInput = null
handleClick = () => {
this.textInput.focus()
}
render() {
return (
<div>
<input type="text" ref={(ref) => (this.textInput = ref)} />
<input type="button" value="Focus the text input" onClick={this.handleClick} />
</div>
)
}
}
или
class CustomTextInput extends React.Component {
textInput = React.createRef()
handleClick = () => {
this.textInput.current.focus()
}
render() {
return (
<div>
<input type="text" ref={this.textInput} />
<input type="button" value="Focus the text input" onClick={this.handleClick} />
</div>
)
}
}
версия с конструктором
class CustomTextInput extends React.Component {
textInput
constructor(props) {
super(props)
this.textInput = React.createRef()
}
handleClick = () => {
this.textInput.current.focus()
}
render() {
return (
<div>
<input type="text" ref={this.textInput} />
<input type="button" value="Focus the text input" onClick={this.handleClick} />
</div>
)
}
}