Answer the question
In order to leave comments, you need to log in
Why doesn't ref work?
class AddDesk extends React.Component {
constructor() {
super();
this.state = {showForm: false};
this.input = React.createRef();
}
handleShowForm() {
this.setState({
showForm: true
});
console.log(this.input);
}
handleHideForm() {
this.setState({
showForm: false
});
}
render() {
let deskAddRender;
{
if ( !this.state.showForm ) {
deskAddRender = (
<button onClick={ this.handleShowForm.bind(this) }>Добавить еще одну колонку</button>
);
} else {
deskAddRender = (
<div className="desk__add_form">
<input type="text" className="title_active" placeholder="Введите заголовок списка" maxLength="512" ref={ (node) => this.input = node }/>
<button className="green_btn">Добавить список</button>
<button className="cancel_btn" onClick={ this.handleHideForm.bind(this) }><img src="img/icons/close.svg" alt="Отмена" /></button>
</div>
);
}
}
return (
<div className="desk__add">
{ deskAddRender }
</div>
);
}
}
Answer the question
In order to leave comments, you need to log in
You incorrectly specify. If you pre-defined ref via createRef, then you don't need to write an arrow function in the ref attribute, just specifying the
UPD property is enough: ah, that's not your problem. At the time of the console.log execution in the handleShowForm, the ref has not yet been created, because the form is not drawn. this.setState is an asynchronous function, it doesn't immediately call the render function to show your field. setState has a callback that is executed after the state has changed. write like this
this.setState({
showForm: true
}, () => {
console.log(this.input);
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question