Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to use React refs to focus a Redux-Form Field when it mounts.

When I try this.refs.title.getRenderedComponent().focus() in componentDidMount, an error is thrown saying:

edit_fund.js:77 Uncaught TypeError: Cannot read property 'getRenderedComponent' of undefined

When I console.log this.refs, it is mostly an empty object and sometimes identifies 'title' as being a ref, but it is not dependable.

Am I using refs incorrectly? My code is below for reference.

componentDidMount = () => {
  this.refs.title
  .getRenderedComponent()
  .focus();
}

...

 <Field
    id="title"
    name="title"
    component={FormInput}
    type="text"
    ref="title" withRef
 />
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
788 views
Welcome To Ask or Share your Answers For Others

1 Answer

Please try setting ref using callback function:

ref={(input) => { this.title = input; }}

and then use this to get underlying DOM node:

ReactDOM.findDOMNode(this.title).focus();

of if DOM input element is wrapped in another element:

ReactDOM.findDOMNode(this.title).getElementsByTagName("input")[0].focus()

According to React docs using refs with a string have some issues. Please check docs for more details.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...