react父子组件传值

父组件给子组件传值

  class类组件,父组件在子组件上写入属性,子组件通过this.props.属性名获取值

  函数式组件,父组件在子组件上写入属性,子组件需要把props作为组件参数才能使用props

子组件给父组件传值

  通过传递回调函数的方式,父组件给子组件传一个回调函数(可带参数),子组件通过this.props.回调函数名,通过调用回调函数,传入参数来传值

父组件

// import React, { useState } from 'react'
// import A from './A'
// export default function F() {
//     const [list, setList] = useState([1, 2, 3])
//     return (
//         <div>
//             <A title='rql' list={list}></A>
//         </div>
//     )
// }

import React, { Component } from 'react'
import A from './A'
export default class F extends Component {
    state = {
        name: 'rql'
    }
    render() {
        return (
            <div>
                <A title="123" event={(value) => {
                    this.setState({
                        name: value
                    });
                }}></A>
                {this.state.name}
            </div>
        )
    }
}

子组件

// import React from 'react'

// export default function A(props) {
//     let { title, list } = props
//     return (
//         <div>
//             {title}{console.log(list)}
//         </div>
//     )
// }

import React, { Component } from 'react'

export default class A extends Component {
    render() {
        return (
            <div>
                {this.props.title}
                <button onClick={() => {
                    this.props.event('子组件给我父组件传的值')
                }}>按钮</button>
            </div>
        )
    }
}

 

posted @ 2022-03-16 11:47  二王戏木  阅读(587)  评论(0)    收藏  举报