问题描述
是否可以通过浏览器(从另一个脚本内部或通过控制台)访问并设置现有React组件的状态和道具?
Is there a possibility to access and set the state and props of an existing React component through the browser (from inside another script or through console)?
我知道Angular提供了一种访问范围和更改变量的方法,但是使用React,我一直无法找到一种方法.
I know there is a way with Angular to access the scope and change variables, but with React I haven't been able to find a way.
我认为一定有办法,因为Facebook的React Developer Tools扩展能够从页面上的React组件获取所有信息(道具,状态,组件,事件监听器),并且可以更改它们
I would assume there must be some way because the React Developer Tools extension from Facebook is able to get all the information (Props, State, Component, Event Listeners) from the React components on the page, with the possibility to change them.
如果有可能通过JavaScript做到这一点,那将是这样做的方式?
If there is a possibility to do this through JavaScript, which would be the way to do it?
推荐答案
如果您拥有 React devtools扩展,您可以使用$r
通过浏览器控制台访问React范围.
If you have the React devtools extension, you can access the React scope via your browser console with $r
.
首先,在React devtools选项卡中选择要操作的组件:
First, select the component you wanna act on in the React devtools tab:
然后,使用$r
对组件起作用,例如使用$r.state
读取状态或使用$r.setState({ ... })
设置状态:
Then, use $r
to act on the component, for example read state with $r.state
or set state with $r.setState({ ... })
:
这篇关于如何从浏览器设置React组件状态和道具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!