React 中的事件总线?

Tom*_*Rup 11 javascript reactjs

我主要使用 Vue,最近才开始使用 React。到目前为止喜欢它,它在很多方面与 Vue 非常相似,这使得学习它变得更容易。

现在,让我们考虑两个兄弟组件。当第二个组件中发生某些事情时,我想触发第一个组件中的某些内容。在 Vue 中,您可以只绑定window.bus = new Vue,然后在其中一个组件中发出bus.$emit('event')并在mounted()第二个组件中绑定bus.$on('event', this.doSth)

你如何在 React 中实现这一点?

Sve*_*een 7

Event Bus只是一个全局函数寄存器,能不能用

class _EventBus {

    constructor() {
        this.bus = {};
    }

    $off(id) {
       delete this.bus[id];
    }

    $on(id, callback) {
        this.bus[id] = callback;
    }

    $emit(id, ...params) {
        if(this.bus[id])
            this.bus[id](...params);
    }
}

export const EventBus = new _EventBus();
Run Code Online (Sandbox Code Playgroud)

export const防止多个实例,使得类的静态


wdm*_*wdm 1

state当通过 向下传递时,父组件可以管理子组件使用的 和 方法props

以下示例递增计数。SibOne显示计数和SibTwo增加计数的按钮。

class App extends Component {
    constructor(props) {
        super(props);
        this.state = {
            count: 0
        };
    }
    incrementCount = () => {
        this.setState({
            count: this.state.count + 1
        });
    }
    render() {
        return (
            <div className="App">
                <SibOne count={this.state.count}/>
                <SibTwo incrementCount={this.incrementCount}/>
            </div>
        );
    }
}

const SibOne = props => <div>Count: {props.count}</div>;

const SibTwo = props => (
    <button onClick={props.incrementCount}>
        Increment Count
    </button>
);
Run Code Online (Sandbox Code Playgroud)

演示: https: //codesandbox.io/s/zqp9wj2n63

有关组件和道具的更多信息:https ://reactjs.org/docs/components-and-props.html

  • 尽管这不是事件总线。 (5认同)