React 开发者工具
你可以使用独立版 React 开发者工具(不是 chrome 的插件)来调试 React 组件层次结构。要使用它,请全局安装react-devtools
包:
注意:react-devtools v4 需要 react-native 0.62 或更高版本才能正常工作。
- npm
- Yarn
npm install -g react-devtools
yarn global add react-devtools
译注:react-devtools 依赖于 electron,而 electron 需要到国外服务器下载二进制包,所以国内用户这一步很可能会卡住。此时请在
环境变量
中添加 electron 专用的国内镜像源:ELECTRON_MIRROR="https://npm.taobao.org/mirrors/electron/"
,然后再尝试安装 react-devtools。
安装完成后在命令行中执行react-devtools
即可启动此工具:
react-devtools
很快就能连上模拟器。
提示:如果你不想全局安装
react-devtools
,可以把它单独加入项目中。用npm install --save-dev react-devtools
命令把react-devtools
包安装到你的项目中,并在package.json
的scripts
中添加"react-devtools": "react-devtools"
,接着在项目根目录下运行npm run react-devtools
命令即可。
If connecting to the emulator proves troublesome (especially Android 12), try running adb reverse tcp:8097 tcp:8097
in a new terminal.
If you prefer to avoid global installations, you can add react-devtools
as a project dependency. Add the react-devtools
package to your project using npm install --save-dev react-devtools
, then add "react-devtools": "react-devtools"
to the scripts
section in your package.json
, and then run npm run react-devtools
from your project folder to open the DevTools.
Integration with React Native Inspector
Open the Dev Menu and choose "Toggle Inspector". It will bring up an overlay that lets you tap on any UI element and see information about it:
However, when react-devtools
is running, Inspector will enter a collapsed mode, and instead use the DevTools as primary UI. In this mode, clicking on something in the simulator will bring up the relevant components in the DevTools:
You can choose "Toggle Inspector" in the same menu to exit this mode.