You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
使用 React.createRef() 来创建Refs,并通过 ref 属性关联到具体的 DOM 节点。React 会在组件挂载时给 current 属性传入 DOM 元素,并在组件卸载时传入 null 值。最终通过 ref 的 current 属性来访问 DOM 节点。 1.在 HTML 元素上使用
classInputFormextendsReact.Component{constructor(props){super(props);// 创建一个 ref 来存储 textInput 的 DOM 元素this.textInput=React.createRef();}focusTextInput=()=>{// 通过 "current" 来访问 DOM 节点this.textInput.current.focus();}render(){return(<div><inputtype="text"ref={this.textInput}/><buttononClick={this.focusTextInput}>focus</button></div>);}}
2.在组件上使用时通过 ref 的 current 属性获取的是组件实例。(不能在函数组件上使用,因为它们没有实例)
在上一篇我们了解到可以在 componentDidMount 或 componentDidUpdate 函数中通过ref属性来访问已经挂载的 DOM 节点或组件实例。ref 属性既可以在组件上使用,也可以在 DOM 节点上使用。
ref的三种用法。
回调函数用法
回调函数就是在 DOM 节点或组件上挂载函数,从而获取到 DOM 节点或组件实例。回调函数在组件被加载或卸载时会立即执行,加载时入参是 DOM 节点或组件实例,卸载时入参时 null。
React.creatRef()用法
使用 React.createRef() 来创建Refs,并通过 ref 属性关联到具体的 DOM 节点。React 会在组件挂载时给 current 属性传入 DOM 元素,并在组件卸载时传入 null 值。最终通过 ref 的 current 属性来访问 DOM 节点。
1.在 HTML 元素上使用
2.在组件上使用时通过 ref 的 current 属性获取的是组件实例。(不能在函数组件上使用,因为它们没有实例)
字符串用法(不推荐使用)
The text was updated successfully, but these errors were encountered: