How to set React component state and props from browser

后端 未结 3 1577
遥遥无期
遥遥无期 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: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.

提交回复
热议问题