首页 > 解决方案 > 如何访问反应组件之外的状态/功能

问题描述

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

我的组件:

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

标签: javascriptreactjs

解决方案


您可以尝试使用Refs来执行此操作。

refOfComponent.setState({ ... })

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


推荐阅读