reactjs onclick函数更改

时间:2019-11-04 12:58:21

标签: javascript reactjs

我仍在使用我的第一个React应用,现在我正尝试通过按表头创建排序选项 所以问题是,按下按钮后,我不知道如何更改onClick功能。

我想要什么: 如果我按<th>first name</th>表应该按名称ASC排序,那么如果我第二次按它,则表数据应该按DESC排序。

非常感谢您的帮助:)

class App extends Component{


  state = {
    carowner: [],
    owner:
    {

        first_name:'',
        last_name:'',
        phone:'',
        email:''
    },
    delowner:
    {
      owner_id:''
    }
  }
componentDidMount()
{
 this.getOwners();
}
getOwners = _ =>{
  fetch('http://localhost:4000/owners')
  .then(response => response.json())
  .then(response => this.setState({ carowner: response.data }))
  .catch(err => console.error(err))
}
addOwner = _ =>
{
    const {owner} = this.state;
    fetch(`http://localhost:4000/owners/add?first_name=${owner.first_name}&last_name=${owner.last_name}&phone=${owner.phone}&email=${owner.email}`)
    .then(this.getOwners)
    .catch(err => console.error(err))
}

delOwner = (evt,owner_id) =>
{
  fetch(`http://localhost:4000/owners/delete?owner_id=${owner_id}`)
  .then(this.getOwners)
  .catch(err => console.error(err))
}

getOwnersByNameASC = _ =>{
  fetch('http://localhost:4000/owners/sort/bynameasc')
  .then(response => response.json())
  .then(response => this.setState({ carowner: response.data }))
  .catch(err => console.error(err))

}

getOwnersByNameDESC = _ =>{
  fetch('http://localhost:4000/owners/sort/bynamedesc')
  .then(response => response.json())
  .then(response => this.setState({ carowner: response.data }))
  .catch(err => console.error(err))

}

renderCarOwner = ({owner_id,first_name,last_name,phone,email}) => <tr key={owner_id}><td>{owner_id}</td><td>{first_name}</td><td>{last_name}</td><td>{phone}</td><td>{email}</td><td><button onClick={(evt) => {this.delOwner(evt,owner_id)}}>Delete</button></td></tr>
render()
{
  const {carowner,owner,delowner} = this.state;
return(
  <div className="centerblock">
  <div>
  <input value={owner.first_name} onChange={e => this.setState({owner:{...owner, first_name: e.target.value}})}/>
    <input value={owner.last_name} onChange={e => this.setState({owner:{...owner, last_name: e.target.value}})}/>
    <input value={owner.phone} onChange={e => this.setState({owner:{...owner, phone: e.target.value}})}/>
    <input value={owner.email} onChange={e => this.setState({owner:{...owner, email: e.target.value}})}/>
    <button onClick={this.addOwner}>Add owner</button>


  </div>

  <table >
  <tr>
                <th>ID</th>
                <th onClick=/* - F() - */>First name</th>
                <th>Last name</th>
                <th>Phone</th>
                <th>Email</th>
                <th>Action</th> 
                </tr>
{carowner.map(this.renderCarOwner)}
</table>

  </div>
);
}
}
export default App;

0 个答案:

没有答案