ReactJs:如何获取引用来自其父级的组件的引用 [英] ReactJs: How to get ref of a component whose ref comes from its parent

查看:52
本文介绍了ReactJs:如何获取引用来自其父级的组件的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如在这个问题中所建议的,这就是引用的方式建议在我想引用子组件时使用.

findDOMNode(childComponentStringRef)

class 字段扩展组件 {componentDidMount() {//this.inputNode.focus();//基本上我也想访问 ref 以在此处输入}使成为() {返回 (<input type='text' ref={this.props.inputRef}/>)}}类 MyComponent 扩展组件 {componentDidMount() {this.inputNode.focus();}使成为() {返回 (<div>你好,<Field inputRef={node =>this.inputNode = node}/>

)}}

我想要的是访问 ref,在 Field 组件中也提供给 input .那么我们该怎么做呢?

我尝试使用

  1. this.props.inputRef

  2. this.inputRef

但没有一个有效.请指导我解决这个问题.

解决方案

将另一个引用分配给输入组件,将一个引用分配给字段组件.然后你可以像 this.inputNode.inputRef.focus();

一样访问子输入

class 字段扩展组件 {componentDidMount() {this.inputRef.focus();}使成为() {返回 (<input type='text' ref={ip=>this.inputRef= node}/>)}}类 MyComponent 扩展组件 {componentDidMount() {this.inputNode.inputRef.focus();}使成为() {返回 (<div>你好,<Field ref={node =>this.inputNode = node}/>

)}}

但是您不需要在 componentDidMount 函数中的两个地方都这样做.如果你没有任何其他逻辑,那么你可以在父或子中使用焦点命令

As suggested in this issue, this is how refs are suggested to use in case I want to ref a child component.

findDOMNode(childComponentStringRef)

class Field extends Component {
  componentDidMount() {
    // this.inputNode.focus(); // Basically I want to access the ref to input here as well
  }

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

class MyComponent extends Component {
  componentDidMount() {
    this.inputNode.focus();
  }

  render() {
    return (
      <div>
        Hello, <Field inputRef={node => this.inputNode = node} />
      </div>
    )
  }
}

What I want is to access the ref, given to input inside the Field Component as well. So how can we do that?

I tried using

  1. this.props.inputRef

  2. this.inputRef

But none works. Please guide me on this one.

解决方案

Assign another ref to the input component and one to the Field component. then you can access the child input like this.inputNode.inputRef.focus();

class Field extends Component {
  componentDidMount() {
    this.inputRef.focus(); 
  }

  render() {
    return (
      <input type='text' ref={ip=> this.inputRef= node} />
    )
  }
}

class MyComponent extends Component {
  componentDidMount() {
    this.inputNode.inputRef.focus(); 

  }

  render() {
    return (
      <div>
        Hello, <Field ref={node => this.inputNode = node} />
      </div>
    )
  }
}

However you don;t need to do it at both places in the componentDidMount function. If you don;t have any other logic, then you can just have the focus command in either of the parent or child

这篇关于ReactJs:如何获取引用来自其父级的组件的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆