react子组件向父组件传值

1,113 阅读1分钟

子组件 说明:给子组件一个btnClick事件,定义arry事件作为父组件接收值的事件

import React from 'react';
export default class prop extends React.Component {
    constructor(props){
        super(props)
        this.state={
            list:['red','blue','pink']
        }
    }
    render() {
        return <div>
            <p>我是子组件</p>
            <button onClick={e => this.btnClick(e)}>btn</button>
        </div>
    }
    btnClick(e) {
        this.props.arry(this.state.list)
    }
}

父组件 说明:接收子组件传过来的arry,再自己定义一个hotClick事件,进行接收

import React from 'react';
import Prop from "../../compontes/Prop/Prop.jsx"
export default class Gszc extends React.Component {
    constructor(props) {
        super(props)
        this.state={
            list:[]
        }
    }
    render() {
        return <div>
            <h1>我是父组件</h1>
            <Prop arry={e => this.hotClick(e)}></Prop>
            <ul>
                {this.state.list.map((item,i)=><li key={i}>{item}</li>)}
            </ul>
        </div>
    }
    hotClick(e) {
        this.setState({
            list:e
        })
    }
}