本文主要是介绍重温react-04,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
兄弟组件之间通信
兄弟1
import React, { Component } from 'react'
import pubsub from './pubsub'
export default class learnReact01 extends Component {render() {return (<div>我是兄弟1<button onClick={this.clickMessage}>向兄弟2发信息</button></div>)}clickMessage=()=>{pubsub.publish('message','6666')}
}
兄弟2
import React, { Component } from 'react'
import pubsub from './pubsub'
export default class learnReact01 extends Component {state = {msg: ""}render() {return (<div>我是兄弟2<div>{this.state.msg}</div></div>)}componentDidMount() {pubsub.subscribe('message', (data) => {console.log(data)this.setState({msg: data})})}
}
react中操纵dom和ref
import React, { Component,createRef } from 'react'
import LearnReact from './learnReact04'
export default class learnReact03 extends Component {constructor(props) {super(props)this.state = {name: '张三'}this.divRef = createRef(null)this.learnReactRef = createRef(null)this.buttonRef = createRef(null)}render() {return (<div><div ref={this.divRef}>我是父组件</div><LearnReact ref={this.learnReactRef} /><button ref={this.buttonRef} onClick={this.onclickThisMessage}>点击</button></div>)}componentDidMount() {console.log(this.divRef.current);console.log(this.learnReactRef.current);console.log(this.buttonRef.current);}onclickThisMessage=()=>{this.learnReactRef.current.onclick()}
}
这篇关于重温react-04的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!