react知识补漏2
react 组件state和方法可以有另外一种形式,减少代码量
import React from "react"
class useOtherstate extends React.Component{
state = {
demo:'useOtherstate'
} //不用变量修饰符的
demoevent = () =>{
const { demo } = this.state;
console.log("res:",demo);
} //不用变量修饰符的
render(){
return (
<div className="userother" onClick={this.demoevent}>
<h3>{this.state.demo}</h3>
</div>
);
}
}
export default useOtherstate;
组件通信
父到子 是props传递到子组件 传变量
子到父 通过传递函数,子组件调用父组件方法
兄弟通信,可以使用第三方库 PubSub.js https://www.npmjs.com/package/pubsub-js
耐心等,真的好久...
import PubSub from 'pubsub-js'
class avatarname extends React.Component{
componentDidMount(){
console.log("i am from avatarname");
PubSub.subscribe('pubevent',(msg,data)=>{
this.setState({name:data});
})
}
class Avatar extends React.Component{
pub = ()=>{
PubSub.publish('pubevent', 'hello world!');
}