[英]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.