2

我有以下功能组件,它呈现 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}

谢谢

4

1 回答 1

1

您可以发送一个回调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 中调用该函数。这会将数据设置为其父组件。

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

    const handleChange = // Update your handleChange to also call setSelection

那应该这样做。

于 2020-01-24T04:58:55.403 回答