我有一个行组件,我正在将其导入到我的 App.js 组件中,显然我可以向该行添加新项目,但删除功能似乎不起作用。我正在传递索引和拼接,但我不确定我做错了什么。任何人都可以建议我哪里出错了吗?
我的 App.js 或我的根组件如下所示:-
import React, {Component} from 'react';
import './App.css';
import Row from './Row.js'
class App extends Component {
state = {
rows: [
{value: 'row1', options:[1,2,3,4,5] },
{value: 'row2', options:[1,2,3,4,5] },
{value: 'row3', options:[ 1,2,3,4,5 ]}
]
}
updateValue = (e, idx) => {
const rows = [...this.state.rows];
rows[idx].value = e.target.value;
this.setState({
rows,
});
}
addRow = () => {
const rows = [...this.state.rows, {value:''}];
this.setState({
rows,
});
}
deleteRow = (idx) => {
const copy = [...this.state.rows]
copy.splice(idx,1)
this.setState ({
rows:copy
})
}
render() {
return (
<div>
{
this.state.rows.map ( (row,idx) => {
return (
<Row
key = {idx}
value = { row.value }
onChange = { (e) => this.updateValue(e,idx) }
delete = { this.deleteRow.bind(this,idx) } />
)
})
}
<button onClick = {this.addRow}> Add </button>
</div>
)
}
}
export default App;
我的行组件如下所示:-
import React from 'react'
const Row = ( props) => {
return (
<div>
<input value= { props.value } onChange={ props.onChange }></input>
<select>
<option></option>
</select>
<select>
<option></option>
</select>
<button onClick = { props.deleteRow } > Delete </button>
</div>
)
}
export default Row
因此,deleteRow
方法似乎不起作用。有人可以纠正我做错了什么以及我应该如何将选项值分配给选择的下拉列表。谢谢。
最佳答案
您传递给组件的属性是delete
,而不是deleteRow
。因此,您的 Row
组件中的这一行:
<button onClick = { props.deleteRow } > Delete </button>
应改为:
<button onClick = { props.delete } > Delete </button>
或者更好的是,更改传递 prop 的方式,使其实际上称为 deleteRow
。因此,您可以将应用 render
函数更改为:
render() {
return (
<div>
{
this.state.rows.map ( (row,idx) => {
return (
<Row
key = {idx}
value = { row.value }
onChange = { (e) => this.updateValue(e,idx) }
deleteRow = { this.deleteRow.bind(this,idx) } />
)
})
}
<button onClick = {this.addRow}> Add </button>
</div>
)
}
}
设置select
标签中的选项:
首先,您需要将选项作为 props 传递给 Row
组件。因此,在您的 App
render
中,您可以执行以下操作:
render() {
return (
<div>
{
this.state.rows.map ( (row,idx) => {
return (
<Row
key = {idx}
value = { row.value }
options = { row.options }
onChange = { (e) => this.updateValue(e,idx) }
deleteRow = { this.deleteRow.bind(this,idx) } />
)
})
}
<button onClick = {this.addRow}> Add </button>
</div>
)
}
}
然后,在您的 Row
组件中,使用新的 options
属性:
const Row = ( props) => {
let options = props.options.map(opt => <option key={opt}>{opt}</option>);
return (
<div>
<input value= { props.value } onChange={ props.onChange }></input>
<select>
{options}
</select>
<button onClick = { props.deleteRow } > Delete </button>
</div>
)
}
关于javascript - 使用 ReactJS 删除 onClick 项目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59924070/