[英]How to use onClick event with <Link> in reactjs
我試圖通過單擊獲取學生的ID。 但這給了我類似TypeError的錯誤:無法讀取未定義的屬性'handleClick'。 這是怎么了?? 首先,我需要使此handleClick函數正常工作。
這是我的反應代碼:
class Premontessori extends React.Component{
constructor(props){
super(props);
this.state={
post:[],
id:[]
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(event) {
alert(event);
}
componentDidMount(){
let self = this;
axios.get('http://localhost:8080/list')
.then(function(data) {
//console.log(data);
self.setState({post:data.data});
self.setState({id:data.data})
});
}
render(){
console.log(this.state.id);
return(
<div className="w3-container">
<div className="w3-display-container">
<div className="w3-panel w3-border w3-yellow w3-padding-4 w3-xxlarge ">
<p >List Of Students</p>
<div className="w3-display-right w3-container">
<Link className="w3-btn-floating w3-yellow" style={{textDecoration:'none',float:'right'}} to="/createstudent">+</Link>
</div></div>
</div>
<ul className="w3-ul w3-card-4 w3-yellow"> {this.state.post.map(function(item, index) {
return (
<Link to="/displaylist" style={{textDecoration:'none'}} key={index} onClick={this.handleClick}>
<li className=" w3-hover-green w3-padding-16" >
<img src={require('./3.jpg')} className="w3-left w3-circle w3-margin-right " width="60px" height="auto" />
<span>{item.Firstname}</span><br/><br/>
</li>
</Link>
)}
)}
</ul>
</div>
);
}
}
export default Premontessori;
當您將this.handleClick
傳遞給Link時,在事件發生並執行函數時,后者發生在Link實例的上下文中。 並且由於Link組件沒有handleClick
屬性,因此操作失敗。
嘗試以在實例化時綁定到當前組件的方式聲明handleClick
:
handleClick = event => {
alert(event);
}
或在render
函數中使用Function#bind
:
<Link onClick={this.handleClick.bind(this)} />
Link
已經具有一個用於單擊的內部處理程序,可以重定向到另一條Route,它是一種標記解決方案。
React Router還提供了一個非標記解決方案來重定向瀏覽器browserHistory.push
。
因此:
import {browserHistory} from 'react-router'
handleClick(event) {
event.preventDefault();
alert('you clicked me');
browserHistory.push('/displaylist');
}
<a style={{textDecoration:'none'}} key={index} onClick={this.handleClick}></a>
代替
import {Link} from 'react-router'
<Link to="/displaylist" style={{textDecoration:'none'}} key={index} onClick={this.handleClick}>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.