2017-11-01 1 views
0
export class UsersTable extends React.Component { 

    constructor() { 
    super(); 
    this.state = { 
     info: null 
    }; 
} 

componentWillMount() { 
      fetch("http://localhost:8081/milltime/getUsers") 
     .then(res => res.json()) 
     .then(info => { 
      this.setInfo(info); 
     }); 
} 

setInfo(info) { 
    const state = this.state; 
    state['info'] = info; 
    this.setState(state); 
} 


render() { 
     const info = this.state.info; 
    if (!this.state.info) { 
     return null; 
    } 

    let listItems = []; 
    for (var i = 0; i < info['mta:getUsersResponse']['mta:users'].length; i++) { 
     listItems.push(
      <tr> 
       <td>{info['mta:getUsersResponse']['mta:users'][i]['mta:UserId']}</td> 
       <td>{info['mta:getUsersResponse']['mta:users'][i]['mta:FullName']}</td> 
       <td>{info['mta:getUsersResponse']['mta:users'][i]['mta:CostHour']}</td> 

      </tr>); 
    } 

    return(
<div className="usersTable"> 
    <Table striped bordered condensed responsive hover> 
    <thead> 
     <tr> 
     <th>Id</th> 
     <th>Full Name</th> 
     <th>Hour cost</th> 
     </tr> 
    </thead> 
     <tbody> 
     {listItems} 
     </tbody> 
    </Table> 
</div> 
); 
} 
    } 

이것은 사용자를 확보하고 데이터 3 열을 표시하는 테이블에 대한 코드입니다. 내가 겪고있는 문제는 테이블을 선택할 수 있다는 것입니다. 테이블을 선택하면 해당 셀의 데이터를 가져 와서 선택한 셀의 사용자 ID를 사용하여 검색 할 수 있습니다. 누구나 깔끔한 해결책을 얻었습니까? 나는 React bootstrap을 사용하고있다.반응 부트 스트랩 테이블에서 표 셀을 선택하십시오.

+0

온 클릭을? https://reactjs.org/docs/handling-events.html –

답변

0

행을 만들 때 onClick 처리기를 바인딩하십시오. 코드의 주석을 참조하십시오.

https://reactjs.org/docs/handling-events.html

export class UsersTable extends React.Component { 

     constructor() { 
     super(); 
     this.state = { 
      info: null 
     }; 
    } 

    componentWillMount() { 
     fetch("http://localhost:8081/milltime/getUsers") 
      .then(res => res.json()) 
      .then(info => { 
       this.setInfo(info); 
      }); 
    } 

    setInfo(info) { 
     const state = this.state; 
     state['info'] = info; 
     this.setState(state); 
    } 

    onSelectedRow(user, clickEvent){ 
     //your user object and the click event 
     //clickEvent.currentTarget = the cell clicked 
    } 

    render() { 
     const info = this.state.info; 
     if (!this.state.info) { 
      return null; 
     } 

     let listItems = []; 
     for (var i = 0; i < info['mta:getUsersResponse']['mta:users'].length; i++) { 
      const user = info['mta:getUsersResponse']['mta:users'][i]; //dryer 
      //Bind you onclick handler to the context and you user object (or id if thats what you want) 
      listItems.push(
       <tr onClick={this.onSelectedRow.bind(this, user)}> 
        <td>{user['mta:UserId']}</td> 
        <td>{user['mta:FullName']}</td> 
        <td>{user['mta:CostHour']}</td> 
       </tr>); 
     } 

     return(
    <div className="usersTable"> 
     <Table striped bordered condensed responsive hover> 
     <thead> 
      <tr> 
      <th>Id</th> 
      <th>Full Name</th> 
      <th>Hour cost</th> 
      </tr> 
     </thead> 
      <tbody> 
      {listItems} 
      </tbody> 
     </Table> 
    </div> 
    ); 
    } 
    } 
0

API는 docs 반응에 설명 된대로 componentDidMount 라이프 사이클 이벤트에서 처리되어야합니다 요청합니다.

또한 귀하의 상태가 setInfo 일 때 돌연변이가 발생하고 있으며 이는 좋은 습관이 아닙니다.

setInfo(info) { 
    this.setState({ 
    info: info, 
    }) 
} 

하거나 코드에서 모든 mta:**를 교체 문제

setInfo(info) { 
    this.setState({ 
    info, 
    }) 
} 

미래에 당신의 API를 변경, 당신은 할거야해야 객체 속기를 사용 : 직접처럼 상태를 업데이트 할 수 있습니다. 당신은 상태에 따라 map을 왜 보지 않으시겠습니까?

this.setState({ 
    info: { 
    users: info['mta:getUsersResponse']['mta:users'].map(user => ({ 
     id: user['mta:UserId'], 
     fullName: user['mta:FullName'], 
     costHour: user['mta:CostHour'], 
    })) 
    } 
}) 

클릭 처리는하는 UserRow 구성 요소를 만들 소품으로 user을 보내고 onClick에 변경 내용을 전파, 지금부터 쉽게된다.

const UserRow = ({ user, onClick }) => 
    <tr onClick={onClick}> 
    <td>{user.id}</td> 
    <td>{user.fullName}</td> 
    <td>{user.costHour}</td> 
    </tr> 

이제 수 map 당신의 상태가 소품 전파 비록 : (당신이 행을 의미하는 경우 또는 TR)를 에

const UserRow = ({ user, onClick }) => 
 
    <tr onClick={onClick}> 
 
    <td>{user.id}</td> 
 
    <td>{user.fullName}</td> 
 
    <td>{user.costHour}</td> 
 
    </tr> 
 

 
class App extends React.Component { 
 
    constructor() { 
 
    super() 
 

 
    this.state = { 
 
     info: { 
 
     users: [ 
 
      { id: 0, fullName: 'User 1', costHour: 100 }, 
 
      { id: 1, fullName: 'User 2', costHour: 50 }, 
 
      { id: 2, fullName: 'User 3', costHour: 150 } 
 
     ] 
 
     } 
 
    } 
 

 
    this.handleUserClick = this.handleUserClick.bind(this) 
 
    } 
 

 
    handleUserClick(user) { 
 
    console.log(`user ${user.id} has been clicked`) 
 
    } 
 

 
    render() { 
 
    return (
 
     <div className="usersTable"> 
 
     <table striped bordered condensed responsive hover> 
 
     <thead> 
 
      <tr> 
 
      <th>Id</th> 
 
      <th>Full Name</th> 
 
      <th>Hour cost</th> 
 
      </tr> 
 
     </thead> 
 
      <tbody> 
 
      {this.state.info.users.map(user => 
 
       <UserRow 
 
       key={user.id} 
 
       user={user} 
 
       onClick={this.handleUserClick.bind(this, user)} 
 
       /> 
 
      )} 
 
      </tbody> 
 
     </table> 
 
    </div> 
 
    ) 
 
    } 
 
} 
 

 
ReactDOM.render(
 
    <App />, 
 
    document.getElementById('root') 
 
)
<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="root"></div>