javascript - 如何访问反应组件之外的状态/功能
问题描述
我正在尝试实现策略设计模式以动态更改我在反应组件中处理鼠标事件的方式。
我的组件:
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');
}
}
解决方案
推荐阅读
- typo3 - 非管理员用户的后端权限问题 | 错字3 8.7.24
- python - 使用 Python 使用另一个表更新 SQL
- javascript - 如何在 javascript 对象中进行模式匹配
- c - 如何通过if语句获取用户信息?
- ios - window?.subviews[1] 应用程序在 iOS 13 中崩溃
- python - 第二次执行os.walk时找不到目录
- apache - 搞砸了 url 重写
- python - 自动 Webscrape Bloominberg
- angular - firestore .update() 在服务器中以角度完成后如何运行代码
- python - 没有numpy,无法在python的二维矩阵中打印第一行或第一列名称。只会打印矩阵中的浮点数