Answer the question
In order to leave comments, you need to log in
Why can't assign ref to a DOM element?
class Prompt extends Component {
constructor(props){
super(props)
this.input = React.createRef()
this.state = {
value: this.props.value
}
}
componentDidMount(){
console.log(this.input.current ); // null
}
onChange = e => this.setState({ value: e.target.value.trim() });
isValid = () => this.props.value !== this.state.value;
onSave = e => {
e.preventDefault();
if (!this.isValid()) {
return;
}
this.props.onOk(this.state.value);
};
render() {
return (
visible={true}
maskClosable={false}
closable={false}
footer={[
key="submit"
disabled={!this.isValid()}
type="primary"
onClick={this.onSave}
>
{this.props.okText}
,
{this.props.cancelText}
]}
>
{this.props.text}
type="text"
ref={this.input}
onChange={this.onChange}
placeholder={this.props.placeHolder}
/>
);
}
}
Can't assign this.input to component . When accessing this.current, it returns null. Is this my mistake or is it in the library from which I take it?
Answer the question
In order to leave comments, you need to log in
Good day. When a ref is passed to an element in the render method, a reference to that node is available through the ref's current property. -- this is the text from the official React page ( https://ru.reactjs.org/docs/refs-and-the-dom.html )
When called from other methods, this.input.current is not yet defined and returns null
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question