简体   繁体   English

如何访问反应组件之外的状态/功能

[英]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.您可以尝试使用Refs来执行此操作。

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.我发现的解决方案是使用 ref 回调使 DOM 元素成为全局变量。

<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然后,您可以通过访问MyComponent的window.MyComponent用,功能window.MyComponent.method()或状态变量与window.MyComponent.state.MyVar

My App.js:我的 App.js:


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

Other.js:其他.js:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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