我有一个通过映射数组动态构建的表。数组中的每个项都有一行。每个行中的一列是select
。我只希望在单击同一行的下一列中的按钮时显示该列的内容。
我的计划是为我的数组中的每个对象添加一些toggle bool属性,但是当我尝试在我的按钮的onclick中切换它时,我的eslint抱怨,因为我正在尝试修改属性参数我发送到onclick调用的函数。
这样做的恰当方法是什么?
这是表格的代码:
<table>
<tbody>
{myArray.map(row => (
<tr key={`test-${row.name}`}>
<td>
<div className="testClass">{row.id}</div>
</td>
<td>{row.name}</td>
<td>
<Select
options={this.getOptions(row.id)}
onSelect={this.onOptionSelect}
placeholder="Select something"
/>
</td>
<td><button onClick={() => { changeStuff(row); }}>{ row.myToggle ? 'Save' : 'Change something' }</button></td>
</tr>
))}
</tbody>
</table>
答案 0 :(得分:2)
在单击处理程序中,您可以完全更新阵列以显示/隐藏选择选项。
根据我的理解,我尝试创建以下代码段。根据我的理解,这是我想出的方式。我在对象数组中保留了“隐藏”字段。而不是'选择'我使用了一个简单的按钮。你可以相应地改变。希望这可以帮助。
const list = [
{
name: "Person 1",
phone: "123-4567",
id: 11,
hidden:true
},
{
name: "Person 2",
phone: "123-4567",
id: 12,
hidden:true
},
{
name: "Person 3",
phone: "123-4567",
id: 23,
hidden:true
},
{
name: "Person 4",
phone: "123-4567",
id: 34,
hidden:true
},
{
name: "Person 5",
phone: "123-4567",
id: 45,
hidden:true
}
];
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
list: list
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(item) {
let updatedList = this.state.list.map(obj => {
if(obj.id === item.id) {
return Object.assign({}, obj, {
hidden:!item.hidden
});
}
return obj;
});
this.setState({
list : updatedList
});
}
render() {
return (
<div>
<table>
<tbody>
{this.state.list.map(item =>
<tr key={item.itemId}>
<td>
{item.name}
</td>
<td>
{item.phone}
</td>
<td >
<button hidden={item.hidden}> Action </button>
</td>
<td>
<button
className="delete"
onClick={() => this.handleClick(item)}
>
Change
</button>
</td>
</tr>
)}
</tbody>
</table>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("app"));
table td {
font-size: 14px;
font-weight: normal;
padding: 10px;
border: 1px solid #eee;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>