reactjs - React ref.current 在 componentDidMount 中仅在酶测试中为空,而不是实时为空
问题描述
我对测试 React 组件相当陌生,并且正在努力测试使用 React.createRef 创建的 ref。我已经阅读了这个很棒的回复,不确定它是否解决了我的问题。在 ref 回调之前调用 componentDidMount
constructor(props) {
super(props);
this.myRef = React.createRef();
console.log('this.myRef in constructor', this.myRef);
}
此控制台日志返回 null 并且是预期的,因为该组件尚未呈现。
componentDidMount() {
console.log('this.myRef in component did mount', this.myRef);
}
return (
<div className="tab_bar">
<ul ref={this.myRef} className="tab__list direction--row" role="tablist">
{ childrenWithProps }
</ul>
</div>
控制台日志返回 componentDidMount 中的ul
html 元素。这也是预期的,因为组件已渲染。
然而,
当我测试这个组件时:
const children = <div> child </div>;
describe('Tab component', () => {
it('should render', () => {
const wrapper = mount(<Tab>{children}</Tab>);
const ulElement = wrapper.find('ul');
const instance = ulElement.instance().ref;
console.log('instance', instance);
expect(wrapper).toMatchSnapshot();
});
});
我的终端中的控制台日志语句(我的构造函数和 componentDidMount 中的 this.myRef)都说{current: null}
并且instance
未定义。
谁能帮我理解发生了什么?谢谢!
解决方案
我猜这仅在 React 16.3 或更高版本中受支持。并且应该安装 16.3 适配器!检查下面复制的测试实现示例。
class Foo extends React.Component {
constructor(props) {
super(props);
this.setRef = createRef();
}
render() {
return (
<div>
<div ref={this.setRef} className="foo" />
</div>
);
}
}
const wrapper = mount(<Foo />);
const element = wrapper.find('.foo').instance();
expect(wrapper.instance().setRef).to.have.property('current', element);
查看您的代码,以下修复可能会起作用。从实例访问它时,您必须使用您的 ref 的名称“myRef”。
//Component
export default class Tab extends React.Component {
constructor(props) {
super(props);
this.myRef = createRef();
}
componentDidMount() {
console.log("TAB Component Did Mount, REF is : ", this.myRef);
}
render() {
return (
<div className="tab_bar">
<ul
ref={this.myRef}
className="tab__list direction--row"
role="tablist"
>
<li>TEST</li>
</ul>
</div>
);
}
}
//Test
describe("Tab component", () => {
it("Ref should be available in instance", () => {
const wrapper = mount(<Tab />);
const ulElement = wrapper.find("ul");
expect(ulElement.instance()).not.toBeNull();
expect(wrapper.instance()).not.toBeNull();
expect(ulElement.instance()).toBe(wrapper.instance().myRef.current);
});
});
编辑:工作沙箱实例 https: //codesandbox.io/s/enzyme-instance-3rktt
确保您的Adapter 版本和React 版本相同
推荐阅读
- django - django-notifications-hq:如何实现
- python-3.x - 从弹出式 Web 链接下载 zip 文件
- graphql - GraphQL 中具有一对多关系的多态性
- linq - 如何从 IQueryable 中提取 where 子句表达式树
- mysql - SQL:Null 列的计数不正确
- python - Tkinter:从函数返回数组
- java - 一切正常,但仍然出现 -> 键入 Dynamic Web Module 4.0 需要 Java 1.8 或更新版本
- php - 如何在php中上传期间确认后覆盖文件
- gulp - 使 gulp.dest 输出到同一目录
- tensorflow - 喀拉斯 | 如何加载多输入(图像、标量)和多输出(回归)数据