首页 > 解决方案 > React 参考 API 的

问题描述

所以我正在关注 Max 在 Udemy 上的视频教程,在其中一个讲座中,他试图解释Ref Api 在 React 16.3

所以这就是他所做的,在容器类(不是 App.js)的内部,他创建了一个名为的属性this.lastref = React.createRef();,然后在返回 JSX 代码中创建了一个 ref 标签,看起来像这样ref={this.lastref} (这是父组件)

现在在子组件中,他创建了一个看起来像这样的方法

myFocus () {
 this.lastref.current.focus() 
 }

然后在父组件中,他再次在componentDidMount 生命周期中做了类似的事情

  componentDidMount() {
this.lastref.current.myFocus()
}

现在我有两个问题。

[问题部分]

第一:他如何在子组件中使用 this.lastref?这是因为从 Parent 到 child 的单向(或单向)流(this.lastPersonRef is referred from ref={this.lastPersonRef}吗?

第二myFocus我相信恰好是静态方法,所以他不应该在使用它之前启动它吗?

[代码示例]

这是父组件的外观-> [person.js]

import React, { Component } from 'react';
import Person from './persons/person-s';

class Cpersons extends Component {
this.lastref = React.createRef()

  componentDidMount() {
this.lastref.current.myFocus()
}

render (
return {
<Person
        key={el.id}
        click={this.props.cpdelete.bind(index)}
        ref={this.lastref}
        name={el.name}
        age={el.age}
        changed={(event) => this.props.cpchanged(event, el.id)} />
      });
    }
  }

export default Cpersons

这应该是我的子组件- > [person-s.js]

import React, { Component } from 'react';

class Cppersons extends Component {

 myFocus () {
 this.lastref.current.focus() 
 }

 render() {

 //something

 return (

 <div> Something </div>

   )
  }
}
export default Cppersons;

标签: javascriptreactjs

解决方案


ref世界发生了很大变化,React有关它的文档也大不相同。我建议你使用回调方法。

class ParentComponent extends React.Component {
    constructor(props) {
        super(props);
        this.otherComponentRef = null; // Will be set after the first render
    }
    render() {
        return [
            <OtherComponent ref={el => this.otherComponentRef = el} />,
            <ChildComponent reference={this.otherComponentRef} />
        ];
    }
}

推荐阅读