Javascript 在React中导入/导出
因此,我正在学习一些React教程,讲师试图解释forward API和ref API 所以我们有一个像这样的孩子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
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设置为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