React Forward API与Ref API技术疑问:类组件Ref调用问题
解决类组件中Ref Forwarding与聚焦方法的实现问题
嘿,我来帮你理清这个场景下怎么用Ref和Forward API实现需求~你现在的情况是父组件创建了this.lastref,子组件Cppersons的myFocus方法需要调用这个ref指向的DOM元素的focus(),核心是要把父组件的ref转发到子组件内部的目标DOM上,因为类组件不能直接接收父组件传递的ref属性,得借助React.forwardRef来搞定。
方案1:用forwardRef包裹类组件(标准做法)
因为类组件没法直接作为forwardRef的参数,我们可以用一个函数组件包裹它,专门用来接收父组件的ref,再把这个ref绑定到子组件内部需要聚焦的DOM元素上。
修改后的子组件代码:
import React, { Component } from 'react'; // 用forwardRef创建转发容器,接收父组件的ref参数 const Cppersons = React.forwardRef((props, ref) => { class InnerCppersons extends Component { myFocus() { // 直接调用转发过来的ref指向的DOM元素的focus方法 ref.current.focus(); } render() { return ( <div> {/* 把ref绑定到你要聚焦的DOM元素上,比如input */} <input ref={ref} type="text" placeholder="点击按钮就能聚焦我~" /> Something </div> ); } } return <InnerCppersons {...props} />; }); export default Cppersons;
然后父组件里这样用:
import React, { Component } from 'react'; import Cppersons from './Cppersons'; class Parent extends Component { constructor(props) { super(props); // 创建父组件的ref this.lastref = React.createRef(); } // 点击按钮触发聚焦 handleFocus = () => { // 直接调用ref指向的DOM元素的focus方法,更直接 this.lastref.current.focus(); } render() { return ( <div> {/* 把父组件的ref通过forwardRef传递给子组件内部的input */} <Cppersons ref={this.lastref} /> <button onClick={this.handleFocus}>点击聚焦输入框</button> </div> ); } }
方案2:通过props传递ref(简单但非标准)
如果觉得包裹组件麻烦,也可以直接把父组件的ref通过props传递给子组件,这种方式不需要用forwardRef,更简单:
子组件代码修改:
import React, { Component } from 'react'; class Cppersons extends Component { myFocus () { // 通过props拿到父组件传递的ref,调用focus this.props.lastref.current.focus() } render() { return ( <div> {/* 把父组件的ref绑定到目标DOM */} <input ref={this.props.lastref} type="text" /> Something </div> ) } } export default Cppersons;
父组件使用:
import React, { Component } from 'react'; import Cppersons from './Cppersons'; class Parent extends Component { constructor(props) { super(props); this.lastref = React.createRef(); // 如果要调用子组件的myFocus方法,需要创建一个ref指向子组件实例 this.childRef = React.createRef(); } handleFocus = () => { // 调用子组件的myFocus方法 this.childRef.current.myFocus(); } render() { return ( <div> <Cppersons lastref={this.lastref} ref={this.childRef} /> <button onClick={this.handleFocus}>点击聚焦</button> </div> ); } }
关键知识点梳理
React.forwardRef:专门用来让组件接收父组件的ref并转发到内部DOM/子组件,是官方推荐的ref转发方式,适合需要对外暴露内部DOM引用的场景。React.createRef():创建一个ref对象,它的current属性会指向绑定的DOM元素或者类组件实例。- 注意:如果用
forwardRef,父组件传递的ref指向的是你绑定的内部DOM元素,而不是子组件实例;如果需要调用子组件的方法,得额外创建一个ref来获取子组件实例。
内容的提问来源于stack exchange,提问作者user9726696
相关产品推荐
相关产品推荐

