在 React 中管理列表中的输入

Manage Input inside a List in React

我从服务器调用 GET,此请求 return N 个对象的数组。然后在这个数组上,我以这种方式使用 Antd 生成一个列表:

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.Item 都具有相同的值。

如何解决多个 List.Item 的问题?我想到了一个数组,但我没有做到。

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

将您的输入更改为

<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
        });
    }