react兄弟组件传递数据

  • 通过发布/订阅进行传递

在子组件A中 commentDidMount函数中,发布事件,在子组件B中commentDidMount函数中对事件进行监听

import {EventEmitter} from 'events';

const emitter = new EventEitter();

class A extends React.Component {
  clickHandler(data,e) {
    this.setState({
      ...
    });
    emitter.emit('theclick', data);
  }
  render() {
    const data = 'xxx';
    return (
) } }
import {EventEmitter} from 'events';

const emitter = new EventEitter();

class App extends React.Component {
  componentDidMount() {
    this.listenerForTheClick = emitter.on('theclick', (data) => {
      this.setState({
        propForB: data;
      })
    })
  }
  componentWillUnmount() {
    emitter.remove(this.listenerForTheClick);
  }

  render() {
    return (
      
      
    )
  }
}

 

 

你可能感兴趣的:(react)