Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在React中导入/导出_Javascript_Reactjs - Fatal编程技术网

Javascript 在React中导入/导出

Javascript 在React中导入/导出,javascript,reactjs,Javascript,Reactjs,因此,我正在学习一些React教程,讲师试图解释forward API和ref API 所以我们有一个像这样的孩子 import React, { Component } from 'react'; class Cppersons extends Component { myFocus () { this.lastref.current.focus() } render() { //something return ( <div> Something &l

因此,我正在学习一些React教程,讲师试图解释forward API和ref API

所以我们有一个像这样的孩子

import React, { Component } from 'react';

class Cppersons extends Component {

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

 render() {

 //something

 return (

 <div> Something </div>

   )
  }
}
export default Cppersons;
在上面的代码中,我们首先在父组件上创建了this.lastref,因此我认为它来自于父组件(将ref从父组件传递给子组件) 这是父组件

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
import React,{Component}来自'React';
从“./persons/Person-s”导入人员;
类Cpersons扩展组件{
this.lastref=React.createRef()
componentDidMount(){
this.lastref.current.myFocus()
}
渲染(
返回{
this.props.cpchanged(event,el.id)}/>
});
}
}
导出默认Cpersons
所以我的问题是,当方法在子对象中定义时,我们如何在父对象中使用myFocus?另外,myFocus在这里是如何工作的?

如前所述。 ref的值因节点类型而异:

  • 在HTML元素上使用ref属性时,使用React.createRef()在构造函数中创建的ref将接收底层DOM元素作为其当前属性
  • 在自定义类组件上使用ref属性时,ref对象将组件的已装入实例作为其当前实例接收
这么说来,通过查看您的代码,您正在自定义类组件中使用ref,这意味着this.lastref.current是Person的一个实例。 在您的例子中,您正在调用此.lastref.current.myFocus()。 我希望您已经在Person类中定义了myFocus方法。
将该ref设置为Person意味着您可以调用在Person组件中定义的任何方法

@iofjuupasli我想查看文档,但由于某些原因,我无法找到答案。检查这一点,当您说组件的已装入实例为当前组件时,这可能有助于理解您的意思。我的意思是,在您的情况下,this.lastref.current是您的个人自定义组件。因此,您可以访问Person类中定义的所有方法。
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