【问题标题】:ReactJs: How to get ref of a component whose ref comes from its parentReactJs:如何获取引用来自其父组件的组件的引用
【发布时间】:2017-06-15 10:01:22
【问题描述】:

正如issue 中所建议的那样,如果我想引用子组件,建议使用 refs。

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>
    )
  }
}

我想要的是访问引用,在 Field 组件内也提供给 input。那么我们该怎么做呢?

我尝试过使用

  1. this.props.inputRef

  2. this.inputRef

但没有一个有效。请指导我。

【问题讨论】:

    标签: javascript reactjs ref


    【解决方案1】:

    您可以传递一个将 refs 存储在父组件中的函数作为 prop。我已经为你做了一个fiddle 的例子。

    class Field extends Component {
      componentDidMount() {
        this.props.setChildRef('inputRef', this.inputRef);
        this.inputRef.focus(); // Basically I want to access the ref to         input here as well
      }
    
      render() {
        return (
          <input type='text' ref={ip=> this.inputRef= ip} />
        )
      }
    };
    
    
    class MyComponent extends Component {
      componentDidMount() {
        this.inputRef.focus();
      }
    
      setChildRef = (name, ref) => {
        this[name] = ref;
      }
    
      render() {
        return (
          <div>
            Hello, <Field setChildRef={this.setChildRef} ref={node => this.inputNode = node} />
          </div>
        )
      }
    }
    

    【讨论】:

      【解决方案2】:

      将另一个 ref 分配给 input 组件,并将一个 ref 分配给 Field 组件。然后您可以访问子输入,例如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>
          )
        }
      }
      

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

      【讨论】:

      • 它不起作用,因为在这种情况下,我将如何获得子组件的 ref?即我将如何在 MyComponent 中获得input type='text' 的引用??
      • &lt;input type='text' ref={ip=&gt; this.inputRef= node} /&gt; 应该是&lt;input type='text' ref={node=&gt; this.inputRef= node} /&gt;
      猜你喜欢
      • 2019-01-02
      • 1970-01-01
      • 2017-05-07
      • 1970-01-01
      • 1970-01-01
      • 2020-02-12
      • 1970-01-01
      • 2017-05-25
      • 2016-07-01
      相关资源
      最近更新 更多