我有一个组件,它接受输入并将它们添加到列表中并显示它们:
import React, {Component} from 'react'
import {
Form,
Col,
Label,
FormGroup,
Button,
Alert,
Input,
Row,
} from 'reactstrap'
export default class NewSubreddit extends Component {
constructor(props) {
super(props)
this.state = {rules: []}
}
addRule() {
const rule = document.getElementById('new-rule').value
if(rule) {
this.setState(prev => ({
rules: prev.rules.concat(rule),
}))
}
console.log(this.state)
}
deleteRule(e) {
e.preventDefault()
console.log(e.target)
// this.setState(prev => ({
// }))
}
render() {
return (
<React.Fragment>
<Form>
<FormGroup row>
<Label sm={2}>Rules</Label>
<Col sm={10}>
<Row>
<Col>
<Input id='new-rule' type='text' placeholder='Add a rule that members of this community should follow!'/>
</Col>
<Col>
<Button onClick={() => this.addRule()}>ADD RULE</Button>
</Col>
</Row>
</Col>
</FormGroup>
<FormGroup row>
<Col>
{this.state.rules.map((rule) =>
<Alert key={rule} isOpen={true} toggle={this.deleteRule}>{rule}</Alert>
)}
</Col>
</FormGroup>
</Form>
</React.Fragment>
)
}
}
因此,我可以将规则添加到 state
中存在的数组 rules
中。
这里我需要做两件事:
- 限制仅创建固定数量的规则(例如 4 个)。
- 通过切换提醒来删除规则。
我尝试通过尝试访问event.target.value
来在deleteRule
函数中进行删除,但它是未定义
!!
最佳答案
您可以通过此方法删除特定元素:
deleteRule = (idx) => () => {
this.setState({
rules: this
.state
.rules
.filter((s, sidx) => idx !== sidx)
});
}
您必须将函数调用为:
<Col>
{this.state.rules.map((rule,idx) =>
<Alert key={rule} isOpen={true} toggle={this.deleteRule(idx)}>{rule}
</Alert>
)}
</Col>
希望这有帮助
关于javascript - Reactjs - 动态添加、删除数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51380774/