文档介绍了使用 ReactJS 版本16.3+时如何add a ref to a class component。
这是一个使用两个文件的简化工作示例:
MyForm.js文件:
import React, { Component } from 'react';
import MyInput from "./MyInput";
class MyForm extends Component {
constructor(props) {
super(props);
this.myInput = React.createRef();
this.onClick = this.onClick.bind(this);
}
onClick(){
console.log(this.myInput.current.isValid());
}
render() {
return (
<div>
<MyInput ref={this.myInput} />
<button onClick={this.onClick}>Verify form</button>
</div>
);
}
}
export default MyForm;
MyInput.js文件
import React, { Component } from 'react';
class MyInput extends Component {
isValid(){
return true;
}
render() {
return (
<div>
Name :
<input type="text" />
</div>
);
}
}
export default MyInput;
它工作正常,当我单击true
按钮时,控制台显示MyForm
。但是,只要在导出组件之前添加功能,就会抛出错误。例如,我通过react-i18n添加翻译
使用功能导出的MyInput.js文件
class MyInput extends Component {
isValid(){
return true;
}
render() {
const {t} = this.props;
return (
<div>
{t("Name")}
<input type="text" />
</div>
);
}
}
export default translate()(MyInput); // <=== This line is changing
现在,当我单击按钮时,会引发错误:
TypeError:this.myInput.current.isValid不是函数
当我在最后一行删除translate()
时,错误消失了。
我了解到ref已被转换函数返回的新组件破坏。这是一个HOC。我读了Forwarding ref chapter,但是我不明白如何将ref转发到由translate()函数返回的组件。
使用 reacti18next 中的translate
以及 redux
connect
函数的结果后,我就遇到了这个问题
我找到了a solution using onRef props和ComponentDidMount,但是一些贡献者认为这是一种反模式,我想避免这种情况。
有没有一种方法可以创建一个包装器来捕获translate()或connect()的HOC结果并将ref添加到此HOC结果中?