一、组件通信
//props通信(适用于父子组件传递)
class App extends React.Component {
render() {
return (
<div>
{ this.props.name }
</div>
);
}
}
ReactDOM.render(
<App name={ hello world } />,
document.getElementById('root')
);
第三方库(下载pubsub-js)
https://github.com/mroderick/PubSubJS
//pubsub通信(适用于父孙、兄弟组件传递)
import PubSub from 'pubsub-js' //安装后引入
class App extends React.Component {
PubSub.publish('name', 'hello world!'); //发布消息
render() {
return (
<div>
hello
</div>
);
}
}
class Name extends React.Component {
componentDidMount() {
//订阅消息
PubSub.subscribe('name', (msg, data) => {
console.log( msg, data );
});
}
render() {
return (
<div>
hello
</div>
);
}
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
网友评论