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



我正在尝试实现策略设计模式,以动态更改我在react组件中处理鼠标事件的方式。

我的组件:

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>
}
}

我想要我的鼠标策略,将访问改变组件不同的方法来处理鼠标事件

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');
}
}

您可以尝试使用Refs来完成此操作。

refOfComponent.setState({ ... })

但我建议您避免这样的构造,因为这可能会增加代码库的复杂性。

我发现的解决方案是使用ref回调使DOM元素成为全局变量。

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

然后,您可以使用window.MyComponent访问MyComponent,使用window.MyComponent.method()访问函数或使用window.MyComponent.state.MyVar访问状态变量

我的应用程序js:


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

</div>
);
}

Other.js:

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

最新更新