将数据从功能组件发送到父组件

问题描述 投票:0回答:1

我具有以下功能组件,可呈现3个复选框(Shopify Polaris):

function CustomersList() {
    const [selected, setSelected] = useState(['hidden']);

    const handleChange = useCallback((value) => setSelected(value), []);

    return (
        <ChoiceList
            allowMultiple
            title="Customers:"
            choices={[
                {
                    label: 'Customer 1',
                    value: 'customer1',
                },
                {
                    label: 'Customer 2',
                    value: 'customer2',
                },
                {
                    label: 'Customer 3',
                    value: 'customer3',
                }
            ]}
            selected={selected}
            onChange={handleChange}
        />
    );
}

...和相同的功能。组件用于父组件(都在同一文件中):

class ParentComponent extends Component {
    render() {
        return (
            <Page title="Title">
                <Layout>
                    <Layout.Section>
                        <Card title="Customers" sectioned>
                            <CustomersList />

                            <Subheading>
                                Selected customers: {customer_value}
                            </Subheading>
                        </Card>
                    </Layout.Section>
                </Layout>
            </Page>
        )
    }
}

现在,我的问题是如何从func发送和获取客户价值(customer1,customer2等)。组件到父组件,以在此处显示值:Selected customers: {customer_value}

谢谢

reactjs react-hooks react-component react-functional-component
1个回答
0
投票

您可以向CustomersList发送回调,该回调会将一些数据附加到调用方。因此您的父组件可能看起来像这样。

class ParentComponent extends Component {
    state = {
        selection: []
    }

    setSelection(data) {
       this.setState({selection: data});
    }

    render() {
        return (
            <Page title="Title">
                <Layout>
                    <Layout.Section>
                        <Card title="Customers" sectioned>
                            <CustomersList setSelection={this.setSelection}/>

                            <Subheading>
                                Selected customers: {customer_value}
                            </Subheading>
                        </Card>
                    </Layout.Section>
                </Layout>
            </Page>
        )
    }
}

,然后在ChoiceList中调用该函数。会将数据设置为其父组件。

© www.soinside.com 2019 - 2024. All rights reserved.