#reactjs
#reactjs
Вопрос:
Каково право получения значения ref для события в компоненте класса?
class ReactRef extends Component {
constructor(props) {
super(props);
this.buttonValue = React.createRef();
}
hasText() {
console.log(this.buttonValue.current); //Cannot read property 'buttonValue' of undefined
}
render(){
return(
<div>
<button type="text" ref={this.buttonValue} onClick={this.hasText}> Click me </button>
</div>
)
}
}
Ответ №1:
Вам нужно привязать hasText
к правильной области видимости.
Вы можете либо объявить его с помощью функции со стрелкой —
hasText = () => {
// now you have access to this.buttonValue.current
}
Или вы можете привязать его внутри своего конструктора —
constructor(props) {
super(props);
this.buttonValue = React.createRef();
this.hasText = this.hasText.bind(this);
}
Комментарии:
1. Вы были быстрее с вашим ответом. 🙂 Я оставляю свой Codesandbox .