我需要将课程标签格式Component #1
传递给Component #2
。我尝试通过调用另一个组件中的方法来实现此目的。但它没有说Reference Error occurred
。怎么做到这一点?
组件#1:
var CourseCard = React.createClass({
showPapers: function(){
console.log("Clicked:" + this.props.each_course.label);
setCourseName(this.props.each_course.label);
var elem = React.createElement(Papers, {
course : this.props.each_course.label
});
},
render: function() {
return(
<Link to="/papers">
<div className="course_card" onClick={this.showPapers}>
<img className="course_img" src={this.props.each_course.image}/>
<h4>{this.props.each_course.label}</h4>
</div>
</Link>
);
}
});
组件#2:
const Papers = React.createClass({
setCourseName: function(course_name){
console.log("Called setCourseName with name" + course_name);
},
render () {
return (
<h1>List of all papers</h1>
)
}
})
答案 0 :(得分:0)
您可以使用refs来调用其他组件的方法。
组件#1
var CourseCard = React.createClass({
showPapers(){
console.log("Clicked:" + this.props.each_course.label);
this.refs.papers.setCourseName(this.props.each_course.label);
},
render() {
return(
<Link to="/papers">
<div className="course_card" onClick={this.showPapers}>
<img className="course_img" src={this.props.each_course.image}/>
<h4>{this.props.each_course.label}</h4>
</div>
</Link>
<Papers refs="papers"/>
);
}
});
组件#2
const Papers = React.createClass({
setCourseName(course_name){
console.log("Called setCourseName with name" + course_name);
},
render () {
return <h1>List of all papers</h1>;
}
})
但尽可能避免使用道具而不是直接调用组件方法。