首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在React中访问同级组件的refs

在React中,要访问同级组件的refs,可以通过使用回调函数或者React.createRef()来实现。

  1. 使用回调函数: 在父组件中,可以通过将一个回调函数作为props传递给子组件,并在子组件中调用该回调函数并传递子组件的ref作为参数。这样父组件就可以访问子组件的ref。

示例代码如下:

代码语言:jsx
复制
class ParentComponent extends React.Component {
  constructor(props) {
    super(props);
    this.childRef = null;
  }

  getChildRef = (ref) => {
    this.childRef = ref;
  }

  render() {
    return (
      <div>
        <ChildComponent getRef={this.getChildRef} />
        <button onClick={() => this.childRef.focus()}>Focus Child Component</button>
      </div>
    );
  }
}

class ChildComponent extends React.Component {
  constructor(props) {
    super(props);
    this.inputRef = null;
  }

  componentDidMount() {
    this.props.getRef(this.inputRef);
  }

  render() {
    return (
      <input type="text" ref={(ref) => { this.inputRef = ref; }} />
    );
  }
}

在上面的例子中,ParentComponent通过getChildRef方法获取了ChildComponent的ref,并且在按钮的点击事件中调用了子组件的focus方法。

  1. 使用React.createRef(): 在React 16.3及以上版本中,可以使用React.createRef()来创建一个ref对象,并将其赋值给组件的ref属性。然后可以通过该ref对象访问组件的实例。

示例代码如下:

代码语言:jsx
复制
class ParentComponent extends React.Component {
  constructor(props) {
    super(props);
    this.childRef = React.createRef();
  }

  render() {
    return (
      <div>
        <ChildComponent ref={this.childRef} />
        <button onClick={() => this.childRef.current.focus()}>Focus Child Component</button>
      </div>
    );
  }
}

class ChildComponent extends React.Component {
  constructor(props) {
    super(props);
    this.inputRef = React.createRef();
  }

  render() {
    return (
      <input type="text" ref={this.inputRef} />
    );
  }
}

在上面的例子中,ParentComponent通过React.createRef()创建了一个ref对象,并将其赋值给ChildComponent的ref属性。然后可以通过该ref对象的current属性访问子组件的实例,从而调用子组件的方法。

这是React中访问同级组件的refs的两种常用方法。这些方法可以帮助您在React应用程序中有效地访问和操作组件。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

13分33秒

React基础 组件核心属性之refs 3 回调ref中调用次数的问题 学习猿地

7分58秒

React基础 组件核心属性之refs 4 createRef的使用 学习猿地

11分15秒

React基础 组件核心属性之refs 2 回调形式的ref 学习猿地

13分2秒

React基础 组件核心属性之refs 1 字符串形式的ref 学习猿地

11分47秒

React基础 组件核心属性之state 3 react中的事件绑定 学习猿地

10分46秒

024_尚硅谷react教程_类式组件中的构造器与props

7分32秒

React基础 组件核心属性之props 5 类式组件中的构造器与props 学习猿地

19分0秒

React基础 组件核心属性之state 4 类中方法中的this 学习猿地

15分0秒

一年过去了,ChatGPT成就了谁,失落了谁

2分33秒

SuperEdge易学易用系列-如何借助tunnel登录和运维边缘节点

5分57秒

JSP视频教程-01_JSP规范介绍

33分11秒

JSP视频教程-03_JSP文件Java命令书写规则

领券