将映射的按钮ID传递给组件

时间:2019-03-15 16:18:46

标签: javascript reactjs material-ui

我有反应映射,将对象数组映射到它们自己的<cards />中。每张卡都有自己的按钮,可以打开<dialog />。我试图将每个对象的唯一ID传递给相关的对话框组件。目前,无论打开哪个对话框,我都将所有ID传递到<dialog />

每个基于ID的对话框将调用唯一数据,目前我正在获取所有不需要的数据。

            {vehicles !== undefined ? vehicles.map(model => (
                <React.Fragment>
                        <Card>
                            <CardActions className={classes.cardActions}>
                                <Button fullWidth color="#333" onClick={this.handleDialog}>
                                    FIND OUT MORE
                            </Button>
                            </CardActions>
                        </Card>

                    <VehicleDialog
                        key={model.id}
                        onClose={this.handleDialog}
                        open={this.state.open}
                        id={model.id} //passes all IDs to this component
                    />
                </React.Fragment>
            ))
                :
                null
            }

我的手柄是标准的:

handleDialog = () => {
    this.setState({ open: !this.state.open });
};

我已经研究了通过onClick传递ID的解决方案,只是不确定如何将其传递给组件。也许有更好的方法?

1 个答案:

答案 0 :(得分:1)

实际上,这是在循环中渲染多个VehicleDialog。您应该做的是-将VehicleDialog移出循环(我的意思是将map移出循环)。并在映射后渲染它。现在,单击按钮时(在您的state中记下其中model.id要打开VehicleDialog

因此,让我们首先修改您的处理程序,以采用模型的id作为参数。它返回一个设置state.openstate.modelId的函数。因此,无论何时打开对话框,它都会知道要打开哪个模型ID(来自state.modelId)。

handleDialog = (id) => () => {
    this.setState({ 
        open: !this.state.open,
        modelId: id
    });
};

现在,我们将对话框切出循环并修改按钮的onClick道具以反映新的处理程序设计更改。循环之后,呈现一个对话框:

{vehicles !== undefined ? vehicles.map(model => (
    <Card>
        <CardActions className={classes.cardActions}>
            <Button fullWidth color="#333" onClick={this.handleDialog(model.id)}>
                FIND OUT MORE
            </Button>
        </CardActions>
    </Card>
)):null
}

<VehicleDialog
    key={model.id}
    onClose={this.handleDialog}
    open={this.state.open}
    id={this.state.modelId}
/>