最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How does the ref callback work in React? - Stack Overflow

programmeradmin5浏览0评论

The ref property enables us to capture the value of an uncontrolled ponent.

class MyComponent extends Component {
  render() {
     <input type="text" ref={el => this.setState({ myEl: el })}/>
  }
}

How does this work? Presumably input is actually a React ponent that has a property ("prop") ref that takes a callback that is invoked with the wrapper ponent of the field every when ponentDidMount is called?

The ref property enables us to capture the value of an uncontrolled ponent.

class MyComponent extends Component {
  render() {
     <input type="text" ref={el => this.setState({ myEl: el })}/>
  }
}

How does this work? Presumably input is actually a React ponent that has a property ("prop") ref that takes a callback that is invoked with the wrapper ponent of the field every when ponentDidMount is called?

Share Improve this question edited Jun 23, 2017 at 13:05 Andrew Li 58k14 gold badges134 silver badges148 bronze badges asked Jun 23, 2017 at 12:43 Ben AstonBen Aston 55.8k69 gold badges220 silver badges349 bronze badges 1
  • 3 BTW don't mutate state directly! Use setState – Andrew Li Commented Jun 23, 2017 at 12:45
Add a ment  | 

1 Answer 1

Reset to default 7

From the React documentation:

Adding a Ref to a DOM Element

React supports a special attribute that you can attach to any ponent. The ref attribute takes a callback function, and the callback will be executed immediately after the ponent is mounted or unmounted.

[...]

React will call the ref callback with the DOM element when the ponent mounts, and call it with null when it unmounts.

So the ref callback is called after the ponent is mounted to the DOM, with the underlying DOM element as the sole argument. It is also called after unmounting with the argument null.

发布评论

评论列表(0)

  1. 暂无评论