luxianren

React 组件通讯

父传子

 1 import React from 'react'
 2 import ReactDOM from 'react-dom'
 3 
 4 /* 
 5   组件通讯:
 6 
 7   1 父组件 -> 子组件:
 8     1.1 在父组件中提供状态
 9     1.2 给子组件标签传递属性 name,值为:this.state.lastName(状态)
10     1.3 在子组件中通过 props 来获取到父组件中传递过来的数据
11 */
12 
13 class Parent extends React.Component {
14   state = {
15     lastName: '王'
16   }
17 
18   render() {
19     return (
20       <div style={{ border: '1px solid pink' }}>
21         <h1>父组件:老王</h1>
22 
23         <Child name={this.state.lastName} />
24       </div>
25     )
26   }
27 }
28 
29 // 子组件:
30 function Child(props) {
31   console.log('child -> props', props)
32   return (
33     <p>我是老王的儿子(子组件),接收到 父组件 传递过来的数据:{props.name}</p>
34   )
35 }
36 
37 ReactDOM.render(<Parent />, document.getElementById('root'))

子传父(附图)

 1 import React from 'react'
 2 import ReactDOM from 'react-dom'
 3 
 4 import './index.css'
 5 
 6 /* 
 7   组件通讯:
 8 
 9   1 子组件 -> 父组件:
10     1.1 父组件提供一个回调函数( 这个回调函数是由 子组件 调用的 )
11     1.2 将回调函数作为 props 传递给子组件
12     1.3 子组件中通过 props 来调用回调函数
13     1.4 子组件将数据作为回调函数的参数传递
14 */
15 class Parent extends React.Component {
16   state = {
17     msg: ''
18   }
19 
20   // 提供回调函数
21   getChildMsg = data => {
22     console.log('父组件中接收到子组件的数据:', data)
23 
24     this.setState({
25       msg: data
26     })
27   }
28 
29   render() {
30     return (
31       <div className="parent">
32         父组件:{this.state.msg}
33         <Child getMsg={this.getChildMsg} />
34       </div>
35     )
36   }
37 }
38 
39 class Child extends React.Component {
40   handleClick = () => {
41     // console.log('子组件中的props:', this.props)
42     this.props.getMsg('养老金')
43   }
44 
45   render() {
46     return (
47       <div className="child">
48         子组件:
49         <button onClick={this.handleClick}>给父组件传递数据</button>
50       </div>
51     )
52   }
53 }
54 
55 ReactDOM.render(<Parent />, document.getElementById('root'))

 

 

 

分类:

React

技术点:

相关文章: