I have two components. I want to call a method of the first component from the second component. How can I do it?
Here is my code.
First Component
class Header extends React.Component{
constructor(){
super();
}
checkClick(e, notyId){
alert(notyId);
}
}
export default Header;
Second Component
class PopupOver extends React.Component{
constructor(){
super();
// here i need to call Header class function check click....
// How to call Header.checkClick() from this class
}
render(){
return (
<div className="displayinline col-md-12 ">
Hello
</div>
);
}
}
export default PopupOver;
解決方案
You can do something like this
import React from 'react';
class Header extends React.Component {
constructor() {
super();
}
checkClick(e, notyId) {
alert(notyId);
}
render() {
return (
<PopupOver func ={this.checkClick } />
)
}
};
class PopupOver extends React.Component {
constructor(props) {
super(props);
this.props.func(this, 1234);
}
render() {
return (
<div className="displayinline col-md-12 ">
Hello
</div>
);
}
}
export default Header;
Using statics
var MyComponent = React.createClass({
statics: {
customMethod: function(foo) {
return foo === 'bar';
}
},
render: function() {
}
});
MyComponent.customMethod('bar'); // true
我有兩個組成部分。我想從第二個組件中調用第一個組件的方法。我該怎么辦?
這是我的代碼。
第一個組件
類頭擴展了React.Component {
Constructor(){
super() ;
}
checkClick(e,notyId){
alert(notyId);
}
}
導出默認標題;
第二部分
類PopupOver擴展了React.Component {
Constructor(){
super();
//在這里,我需要調用Header類函數check click ....
//如何從此類中調用Header.checkClick()
}
render(){
return(
< div className = displayinline col-md-12>
你好
< / div>
);
}
}
導出默認值PopupOver;
解決方案
您可以執行以下操作
import從'react'進行反應;
類標題擴展了React.Component {
Constructor(){
super();
}
checkClick(e,notyId){
alert(notyId);
}
render(){
return(
< PopupOver func = {this.checkClick} />
)
}
};
類PopupOver擴展了React.Component {
構造函數(props){
super(props ;;
this.props.func(this,1234);
}
render(){
return(
< div className = displayinline col-md-12>
你好
< / div>
);
}
}
導出默認標題;
使用靜態變量
< code> var MyComponent = React.createClass({
statics:{
customMethod:function(foo){
return foo ==='bar';
}
},
render:function(){
}
});
MyComponent.customMethod(’bar’); // true
