admin管理员组

文章数量:1392050

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.

本文标签: javascriptHow does the ref callback work in ReactStack Overflow