javascript - 如何仅在父元素中显示按钮?

标签 javascript reactjs

我有一个小问题。我有一个嵌套表。应删除该表中的第一项。到目前为止一切都还好。但是如何仅在第一个元素上显示“删除用户”按钮?

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/

相关文章:

javascript - react-query - 带分页的 getQueryData 和 setQueryData

javascript - ExtJs 4 : Using two copies of same component in one form

javascript - 使用自定义按钮控制Soundcloud HTML5 Widget Player

javascript - rails 问题中的 select_tag 和 javascript

javascript - Angularjs,对表中的选定复选框应用操作

javascript - Reactjs - 显示组件的多个条件 - if/else block

reactjs - 当使用 redux 和 componentWillMount 时,防止 React 组件渲染两次

javascript - React Dist 无需服务器、 Node 或 Http 服务器

reactjs - 聚光灯不工作,而半球光和点光在我的代码中工作

javascript - 使用 Fabric js 使背景图像适合 Canvas 大小