How to set React component state and props from browser

后端 未结 3 1504
遥遥无期
遥遥无期 2021-02-07 10:10

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)?

I know t

相关标签:
3条回答
  • 2021-02-07 11:00

    To set the state from your browser, stick this somewhere in your component, like in render():

      globalSetState = function(state){this.setState(state)}.bind(this);
    

    Note: It's important to leave off the var, as this is what makes the defined function globally accessible.

    You can now call globalSetState({x: 'y'}) in your console.

    Warning: This is mad ugly, and, like console.log() for debugging, should be deleted in your live app.

    0 讨论(0)
  • 2021-02-07 11:02

    If you have the React devtools extension, you can access the React scope via your browser console with $r.

    First, select the component you wanna act on in the React devtools tab:

    Then, use $r to act on the component, for example read state with $r.state or set state with $r.setState({ ... }) :

    0 讨论(0)
  • 2021-02-07 11:11

    To set a react components's state from the browser, you can bind a function to the window object that will trigger the set state.

    In the react component's constructor, you can do this.

    constructor (props){
        super(props);
        window.changeComponentState = (stateObject) => {
            this.setState ({stateObject});
        }
    }
    

    In the browser console you can do this.

    window.changeComponentState ({a:'a'});
    

    WARNING: This is anti-pattern. This will work, but you should never never do this.

    0 讨论(0)
提交回复
热议问题