react组件通信
2020-06-05 05:25
288 查看
1.父向子传值
import React, { Component } from "react"; import ReactDOM from "react-dom"; function Child(props) { return <div>我是子组件{props.name}</div>; } class Comment extends Component { render() { return <Child name={<h1>Comment的值</h1>}></Child>; } } ReactDOM.render(<Comment name={"zhangsan"} />, document.getElementById("root"));
2.子向父传值
import React from 'react' import ReactDOM from 'react-dom' import './index.css' /* props */ // 父组件 class Parent extends React.Component { state = { parentMsg: '' } // 提供回调函数,用来接收数据 getChildMsg = data => { console.log('接收到子组件中传递过来的数据:', data) this.setState({ parentMsg: data }) } render() { return ( <div className="parent"> 父组件:{this.state.parentMsg} <Child getMsg={this.getChildMsg} /> </div> ) } } // 子组件 class Child extends React.Component { state = { msg: '刷抖音' } handleClick = () => { // 子组件调用父组件中传递过来的回调函数 this.props.getMsg(this.state.msg) } render() { return ( <div className="child"> 子组件:{' '} <button onClick={this.handleClick}>点我,给父组件传递数据</button> </div> ) } } ReactDOM.render(<Parent />, document.getElementById('root'))
兄弟之间传值
import React from 'react' import ReactDOM from 'react-dom' /* 兄弟组件通讯 */ // 父组件 class Counter extends React.Component { // 提供共享状态 state = { count: 0 } // 提供修改状态的方法 onIncrement = () => { this.setState({ count: this.state.count + 1 }) } render() { return ( <div> <Child1 count={this.state.count} /> <Child2 onIncrement={this.onIncrement} /> </div> ) } } const Child1 = props => { return <h1>计数器:{props.count}</h1> } const Child2 = props => { return <button onClick={() => props.onIncrement()}>+1</button> } ReactDOM.render(<Counter />, document.getElementById('root'))
相关文章推荐
- React组件生命周期及组件之间的通信
- 【React源码分析】组件通信、refs、key和ReactDOM
- ReactNative组件间的通信
- ReactJs组件间通信的方法
- React组件通信
- React 组件通信
- React 组件间的通信示例
- React(11)组件通信
- react组件之间的通信
- react中组件通信的几种方式
- React -- 组件间通信
- react系列(三)组件间通信
- React教程(四)——组件传值和通信
- ReactJS组件之间通信
- React中父子组件间的通信问题
- React组件通信(属性传值)
- React中嵌套组件与被嵌套组件的通信
- [转] React 中组件间通信的几种方式
- React 精要面试题讲解(二) 组件间通信详解
- React中父子组件间的通信问题