我正在尝试制作一组可以复制或删除的输入。
我发现并使用了以下组合:https://jsfiddle.net/69z2wepo/36745/这是(因为上面的代码不处理删除):https://codepen.io/lichin-lin/pen/MKMezg
我可能不需要指向特定的输入,因为在我的界面中,您应该始终只在前面的输入已填满的情况下才添加新的输入(我稍后会设置条件),因此只删除最后一个。因此,我可以使用一个简单的计数器作为所有这些问题的解决方案(尽管我需要 3-4 个计数器来处理不同的输入类型)。
/* ************************************* */
/* ******** IMPORTS ******** */
/* ************************************* */
import React, { Component } from 'react';
import { Card, CardBlock, Button, InputGroup, Input } from 'reactstrap';
import ProviderInfos from '../ProviderInfos/ProviderInfos';
/* ************************************* */
/* ******** VARIABLES ******** */
/* ************************************* */
const count = 0;
/* ************************************* */
/* ******** COMPONENT ******** */
/* ************************************* */
export default class SearchExtendedComponent extends Component {
constructor(props) {
super(props);
this.state = { inputList: [] };
this.incrementCount = this.incrementCount.bind(this);
this.decrementCount = this.decrementCount.bind(this);
}
incrementCount() {
const inputList = this.state.inputList;
this.setState({
count: this.state.count + 1,
inputList: inputList.concat(<Input key={count} />),
});
}
decrementCount() {
const inputList = this.state.inputList;
this.setState({
count: this.state.count - 1,
inputList: inputList.concat(<Input key={count} />),
});
}
render() {
return (
<Card>
<CardBlock className="main-table">
<InputGroup>
<Input placeholder="Type1" />
<ProviderInfos />
</InputGroup>
{/* THE IDEA IS TO HAVE AN ADD AND REMOVE BUTTON FOR EACH TYPE */}
<InputGroup className="add-more">
<button onClick={this.incrementCount}>Add input</button>
{this.state.inputList}
</InputGroup>
<InputGroup>
<Input placeholder="Type2" />
<ProviderInfos />
</InputGroup>
<InputGroup>
<Input placeholder="Type3" />
<ProviderInfos />
</InputGroup>
<Button color="secondary">Options</Button>{' '}
<Button id="btn">Exécuter</Button>
</CardBlock>
</Card>
);
}
}
我在控制台中收到错误:
Warning: flattenChildren(...): Encountered two children with the same key, `1:$0`. Child keys must be unique; when two children share a key, only the first child will be used.
这似乎与所发生的情况相符:
在“添加”按钮停止工作之后,仅添加第一个新输入。
正如你所看到的,我目前正在函数中声明输入(或者至少在我看来我是......这不是吗?const inputList = this.state.inputList;
吗?)我认为这就是我应该在“计数”旁边声明的问题,但我尝试这样做:
const inputList = this.state.inputList;
const propTypes = {
inputList: React.PropTypes.inputList,
};
导致应用程序根本无法加载:“无法读取未定义的属性‘状态’”。
不仅如此,这对我来说似乎并不是干净的重构代码,因为我做了两次,并且请记住,我将不得不更多地重复此代码,因为添加和删除功能(和按钮)都会必须有三到四种不同的输入类型。
更新:将删除按钮部分移至另一个问题:React:使用按钮添加/删除组件:删除不起作用