简体   繁体   中英

How to access state / functions outside of react component

I'm trying to implement the strategy design pattern to dynamically change how I handle mouse events in a react component.

My component:

export default class PathfindingVisualizer extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            grid: [],
            mouseLeftDown: false,
        };
        const mouseStrat2 = null;     // Object I will change that has different functions for handling events
    }

    componentDidMount() {
        this.resetGrid();
        this.mouseStrat2 = new StartEndStrat();
    }

    render() {
        //buttons that change the object i want handling mouse events
    <button onClick={() => this.mouseStrat2 = new StartEndStrat(this)}>startendstrat</button>
    <button onClick={() => this.mouseStrat2 = new WallStrat(this)}>wallstrat</button>
    }
}

I want my mouse strats that will access change the component with differing methods to handle mouse events

export class StartEndStrat {
    handleMouseDown(row, col) {
        // I want to access component state and call functions of the component
        this.setState({ mouseLeftDown: true });
        PathfindingVisualizer.resetGrid();
    }
    //other functions to change other stuff

    handleMouseEnter(row, col) {
        console.log('start end strat');
    }
}

export class WallStrat {
    handleMouseDown(row, col) {
        this.setState({ mouseLeftDown: true });
    }

    handleMouseEnter(row, col) {
        console.log('wallstrat');
    }
}

You can try use Refs to do this.

refOfComponent.setState({ ... })

But I would rather recommend you to avoid such constructions as this may add complexity to your codebase.

Solution I found was to use a ref callback to make the DOM element a global variable.

<MyComponent ref={(MyComponent) => window.MyComponent = MyComponent})/>

Then you can access MyComponent with window.MyComponent , functions with window.MyComponent.method() or state variables with window.MyComponent.state.MyVar

My App.js:


function App() {
  return (
    <div className="App">
      <PathfindingVisualizer ref={(PathfindingVisualizer) => {window.PathfindingVisualizer = PathfindingVisualizer}} />
      
    </div>
  );
}

Other.js:

handleMouseDown() {
    window.PathfindingVisualizer.setState({mouseLeftDown: true});
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM