如何在反应中将数组从子组件传递到父组件

时间:2020-02-24 18:22:59

标签: reactjs

如何在反应中将数组从子组件传递到父组件 这是我的代码

这是我的父级组件

import React, { Component } from 'react';
import Child from '../Child/Child';

export default class Parent extends Component {
    render() {
        return (
            <div>
                <Child></Child>
            </div>
        )
    }
}

这是子组件

import React, { Component } from 'react'

export default class Child extends Component {
    render() {
        const students = ['Mark','John'];
        return (
            <div>
            </div>
        )
    }
}

1 个答案:

答案 0 :(得分:1)

使用React组件状态和道具来实现这一目标:

父母:

import React, { Component } from 'react';
import Child from '../Child/Child';

export default class Parent extends Component {
    constructor(props) {
        super(props);
        this.state = {data: []} // Initialize the State
        this.onChildData = this.onChildData.bind(this); // Bind the helper method
    }

    /*
     * This method is just to update the state with new data incoming from Child
     * You can even inline this in your 'render' method
     */
    onChildData(data) {
        this.setState({data});
    }

    render() {
        return (
            <div>
                /*
                 * Add a 'onData' prop to invoke from Child
                 * It will work as a callback
                 */
                <Child onData={this.onChildData}></Child>
            </div>
        )
    }
}


孩子:


import React, { Component } from 'react'

const students = ['Mark','John'];

export default class Child extends Component {
    /**
     * componentDidMount is called by React immediately after this component is mounted
     * We use it to call the 'onData' callback and send data to the parent
     */
    componentDidMount() {
        this.props.onData(students);
    }

    render() {
        return (
            <div>
            </div>
        )
    }
}