mirror of
https://github.com/reactjs/react.dev.git
synced 2026-02-23 20:23:08 +00:00
Make the callback example more similar to the new API
This commit is contained in:
@@ -267,18 +267,25 @@ All things considered, we advise against exposing DOM nodes whenever possible, b
|
||||
|
||||
React also supports another way to set refs called "callback refs", which give more fine-grain control over when refs are set and unset.
|
||||
|
||||
Instead of passing a `ref` attribute created by `createRef()`, you pass a function. The function receives the React component instance or HTML DOM element as its argument, which can be stored and accessed elsewhere. This example uses the `ref` callback to store a reference to a DOM node:
|
||||
Instead of passing a `ref` attribute created by `createRef()`, you pass a function. The function receives the React component instance or HTML DOM element as its argument, which can be stored and accessed elsewhere.
|
||||
|
||||
The example below implements a common pattern: using the `ref` callback to store a reference to a DOM node in an instance property.
|
||||
|
||||
```javascript{6,17}
|
||||
class CustomTextInput extends React.Component {
|
||||
constructor(props) {
|
||||
super(props);
|
||||
this.textInput = { value: null }; // initial placeholder for the ref
|
||||
this.focusTextInput = () => {
|
||||
// Explicitly focus the text input using the raw DOM API
|
||||
this.textInput.focus();
|
||||
// Focus the text input using the raw DOM API
|
||||
this.textInput.value.focus();
|
||||
};
|
||||
}
|
||||
|
||||
componentDidMount () {
|
||||
if (this.textInput) this.focusTextInput() // autofocus the input on mount
|
||||
}
|
||||
|
||||
render() {
|
||||
// Use the `ref` callback to store a reference to the text input DOM
|
||||
// element in an instance field (for example, this.textInput).
|
||||
@@ -286,7 +293,7 @@ class CustomTextInput extends React.Component {
|
||||
<div>
|
||||
<input
|
||||
type="text"
|
||||
ref={(input) => { this.textInput = input; }} />
|
||||
ref={element => this.textInput.value = element} />
|
||||
<input
|
||||
type="button"
|
||||
value="Focus the text input"
|
||||
@@ -300,8 +307,6 @@ class CustomTextInput extends React.Component {
|
||||
|
||||
React will call the `ref` callback with the DOM element when the component mounts, and call it with `null` when it unmounts. `ref` callbacks are invoked before `componentDidMount` or `componentDidUpdate` lifecycle hooks.
|
||||
|
||||
Using the `ref` callback to set a property on the class is a common pattern for accessing DOM elements. The preferred way is to set the property in the `ref` callback like in the above example. There is even a shorter way to write it: `ref={input => this.textInput = input}`.
|
||||
|
||||
You can pass callback refs between components like you can with object refs that were created with `React.createRef()`.
|
||||
|
||||
```javascript{4,13}
|
||||
|
||||
Reference in New Issue
Block a user