在React中管理List中的输入

时间:2018-05-24 08:28:24

标签: reactjs jsx antd

我从服务器调用GET,此请求返回N个对象的数组。然后在这个数组上我用Antd生成一个List:

render() {
        return (
            <List
                dataSource={this.props.images}
                renderItem={image => (
                    <List.Item actions={
                        [
                            <Icon key={"1"+image.Id.toString()} onClick={(e) => this.actionClick('RUN',image.Id, image.RepoTags[0].replace(/[^a-zA-Z0-9]/g,'_'), e)}
                                  className="icon" type="caret-right" />,
                            <Popconfirm placement="topRight" title="Are you sure delete this image?"
                                        onConfirm={(e) => this.actionClick('REMOVE_IMAGE',image.Id, e)} okText="Yes" cancelText="No">
                                <Icon key="4" className="icon" type="close" />
                            </Popconfirm>
                        ]
                    }>
                        <List.Item.Meta
                            title={image.RepoTags[0]}
                            description={image.Labels ? image.Labels.maintainer : ''}
                        </List.Item.Meta>
                            <InputGroup compact className={'inputGroup'}>
                                <Input style={{ width: '50%' }} placeholder={'inner port'} value={this.state.innerPort} onChange={evt => this.updateValue("innerPort",evt)}/>
                                <Input style={{ width: '50%' }} placeholder={'redirect'} value={this.state.redirectPort} onChange={evt => this.updateValue("redirectPort",evt)}/>
                            </InputGroup>

                    </List.Item>
                )}
            >
            </List>
        );
    }

正如您在代码中看到的,我为每个List.Item都有一个InputGroup,并使用以下内容将值存储在状态中:

updateValue(k,v) {
        console.log("key", k, "value", v);
        console.log(this.state);
        this.setState({
            [k]:v.target.value
        });
    }

这里的问题是我对List的每个List.Item都有相同的值。

如何使用多个List.Item管理此问题?我想到了一个阵列,但我没有做到这一点。

2 个答案:

答案 0 :(得分:1)

您是否尝试使用FlatList而不是List,因此您可以将项目索引传递给呈现的项目。

答案 1 :(得分:1)

将输入更改为

<Input style={{ width: '50%' }} placeholder={'inner port'} value={this.state["innerPort"+image.id] } onChange={evt => this.updateValue("innerPort",image.Id,evt)}/>

这将向更新功能发送唯一标识符,然后您可以像

一样使用它
updateValue(k,id,v) {
        console.log("key", k, "value", v);
        console.log(this.state);
        var myKey=k+id
        this.setState({
            [myKey]:v.target.value
        });
    }