gpt4 book ai didi

javascript - 访问包装在高阶组件中的组件中的实例方法 - React.js

转载 作者:行者123 更新时间:2023-11-28 20:14:35 25 4
gpt4 key购买 nike

我正在为我的 React 组件编写一些测试:

let DebugElement = TestUtils.renderIntoDocument(<Debug />);
console.log(DebugElement)
spyOn(DebugElement, 'fetchAndSelect');

但是,它说 fetchAndSelect 不存在。这是真的。

我这样包装我的组件:

import { DragDropContext } from 'react-dnd';

const Debug = React.createClass({
fetchAndSelect() {}
});

export default DragDropContext(HTML5Backend)(Debug);

如果您查看下面的屏幕截图,您会发现我可以在 refs.child 中访问我的组件方法。这是正确的方法吗?

enter image description here

最佳答案

包装的组件实例通过getDecoratedComponentInstance()提供:

let tree = TestUtils.renderIntoDocument(<Debug />);
let DebugElement = tree.getDecoratedComponentInstance();
console.log(DebugElement);
spyOn(DebugElement, 'fetchAndSelect');

您还可以通过包装组件类型上的 DecoratedComponent 访问原始的非包装组件 type,并且可以使用 TestUtils.findRenderedComponentWithType 或其他查找组件的方法:

let tree = TestUtils.renderIntoDocument(<Debug />);
let DebugElement = TestUtils.findRenderedComponentWithType(
tree, Debug.DecoratedComponent
);
console.log(DebugElement)
spyOn(DebugElement, 'fetchAndSelect');

看看 Testing docs了解更多信息。

关于javascript - 访问包装在高阶组件中的组件中的实例方法 - React.js,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32751105/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com