javascript - 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;
解决方案
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} />
];
}
}
推荐阅读
- json - Groovy JsonOutput.toJson(Object) 返回空字符串
- python - 在 python 中是否有任何替代方法来替换运行时中的变量,如 unix shell 脚本 {!variableName}
- node.js - Docker 与 node.js
- c# - 如何使用 Mimekit 从 IOS 保存附件
- sql - 带有插入语句的 CTE 函数
- excel - 如何使用 SharePoint excel Services REST API 更新工作簿中的工作表(可能是单元格)
- linux - 将长参数发送到 python argparser
- php - Angular9 http post CORS问题
- android - 如何在Android中使用retrofit2解析jsonObject发送到字符串?
- ruby-on-rails - 如何从 check_box 中获取哈希值?