我正在尝试制作一组可以复制或删除的输入。
我发现并使用了以下的组合: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;
吗?)我认为这是我应该在“计数”旁边声明的问题“ IMO 但我尝试这样做:
const inputList = this.state.inputList;
const propTypes = {
inputList: React.PropTypes.inputList,
};
导致应用程序根本无法加载:“无法读取未定义的属性‘状态’”。
不仅如此,这对我来说似乎不是干净的重构代码,因为我做了两次,请记住,我将不得不更多地复制此代码,因为添加和删除功能(和按钮)都会必须有三到四种不同的输入类型。
更新:将删除按钮部分移至另一个问题:react:添加/删除带有按钮的组件:删除不起作用