gpt4 book ai didi

ReactJS - 从另一个组件调用一个组件方法

转载 作者:行者123 更新时间:2023-12-03 12:59:21 25 4
gpt4 key购买 nike

我有两个组件。我想从第二个组件调用第一个组件的方法。我该怎么做?

这是我的代码。

第一个组件

class Header extends React.Component{

constructor(){
super();
}

checkClick(e, notyId){
alert(notyId);
}
}

export default Header;

第二个组件

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;

最佳答案

你可以做这样的事情

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;

使用静态

var MyComponent = React.createClass({
statics: {
customMethod: function(foo) {
return foo === 'bar';
}
},
render: function() {
}
});

MyComponent.customMethod('bar'); // true

关于ReactJS - 从另一个组件调用一个组件方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39119537/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com