我有一个小问题。我有一个嵌套表。应删除该表中的第一项。到目前为止一切都还好。但是如何仅在第一个元素上显示“删除用户”按钮?
class UserList extends Component {
constructor(props) {
super(props);
this.state = {
openDetail: false
}
}
parentUserToggle (item, index) {
this.setState({
openDetail: !this.state.openDetail
})
}
render() {
const { userProfile, index } = this.props;
let parentUserItem = null;
if (userProfile.children instanceof Object) {
parentUserItem = userProfile.children.map((children, index) => {
return <UserList key={children.ID} index={index} userProfile={children} />
});
}
return (
<div className="table-row" key={index}>
<div className="col-md-1">
{
userProfile.children ?
<button
className="btn btn-primary"
onClick={this.parentUserToggle.bind(this, userProfile.children)}
>
{ !this.state.openDetail ? 'OPEN' : 'CLOSE' }
</button>
: null
}
</div>
<div className="col-md-3">{userProfile.Name}</div>
<div className="col-md-3">{userProfile.City}</div>
<div className="col-md-3">{userProfile.Phone}</div>
<div className="col-md-2">
{
userProfile || !parentUserItem ?
<button
className="btn btn-danger"
onClick={this.props.removeUser}
> Remove User </button>
: null
}
</div>
<div className={this.state.openDetail ? 'table-true' : 'table-false'}>
{
parentUserItem
}
</div>
</div>
);
}
}
感谢支持。
最佳答案
假设您作为 key
传递的 index
值是从 1 开始的增量数值,您可以执行以下操作:
onClick={Number(index) === 1 ? this.props.removeUser : null}
或者,取决于您想要做什么,但希望这对您有帮助
{
userProfile || !parentUserItem || Number(index) === 1 ?
<button
className="btn btn-danger"
onClick={this.props.removeUser}
> Remove User </button>
: null
}
关于javascript - 如何仅在父元素中显示按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44842869/