[英]Warning: Function components cannot be given refs warning in React using forwardRef
[英]Using react-test-renderer with <Switch> causes "Stateless function components cannot be given refs" warning
我正在使用 react-test-renderer (16.0.0-beta.5) 在自定義 React Native 組件上執行快照測試。 該組件包含一個 Switch 組件,這會導致在測試執行期間拋出此警告:
console.error node_modules\\fbjs\\lib\\warning.js:36
警告:不能為無狀態函數組件提供引用。 嘗試訪問此引用將失敗。
檢查
Switch
的渲染方法。 在 Switch 中的 Unknown(由 Switch 創建)
要重現的最少代碼:
import React from 'react';
import renderer from 'react-test-renderer';
import { Switch } from 'react-native';
test('renders correctly', () => {
const tree = renderer.create(
<Switch />
);
});
更多細節:該問題是由 Switch.render 使用的本機 RCTSwitch 組件引起的:
return (
<RCTSwitch
{...props}
ref={(ref) => { this._rctSwitch = ref; }}
onChange={this._onChange}
/>
);
正如你所看到的,這個組件被分配了一個 ref。 然而,react-test-renderer 使用以下代碼來檢查組件是否是無狀態的:
if (typeof value === 'object' && value !== null && typeof value.render === 'function') {
// Proceed under the assumption that this is a class instance
由於 RCTSwitch 沒有渲染方法,因此會引發警告。 這是一個錯誤嗎?
我將jest.mock('Switch')
到測試中,現在它通過了。
請注意,這樣做會從快照中刪除 Switch 組件,但是由於沒有理由測試純react-native
組件,我認為只要 Switch 使用的所有功能都單獨測試就可以了。
無狀態組件不支持引用,創建一個有狀態組件。
有關更多詳細信息,請參閱此答案
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.