[英]How to access state / functions outside of react 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>
}
}
我希望我的鼠標策略將使用不同的方法來訪問更改組件來處理鼠標事件
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');
}
}
我發現的解決方案是使用 ref 回調使 DOM 元素成為全局變量。
<MyComponent ref={(MyComponent) => window.MyComponent = MyComponent})/>
然后,您可以通過訪問MyComponent的window.MyComponent
用,功能window.MyComponent.method()
或狀態變量與window.MyComponent.state.MyVar
我的 App.js:
function App() {
return (
<div className="App">
<PathfindingVisualizer ref={(PathfindingVisualizer) => {window.PathfindingVisualizer = PathfindingVisualizer}} />
</div>
);
}
其他.js:
handleMouseDown() {
window.PathfindingVisualizer.setState({mouseLeftDown: true});
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.