![](/img/trans.png)
[英]How can i pass a value from a component to another component in ReactJS
[英]In reactjs how can I call a method from another component?
只是尝试reactjs并遇到了我想在另一个组件上调用方法的情况:
class MyComp extends React.Component {
callMe(){
...
}
}
所以mycomp2:
import MyComp from 'myComp';
class MyComp2 extends React.Component {
test(){
MyComp.callMe();
}
}
我怎样才能做到这一点 ?
不能。 您不能在react组件中做到这一点。 唯一的方法是将该功能移交给他们的共同祖先。
当然,还有另一种方法,为什么不考虑使用redux? 让我们通过redux状态来响应组件对话。 这样,您将永远不会遇到这个难题。
如果方法callMe不使用this ,则可以将其清除为静态状态,以使用它。
class MyComp extends React.Component {
static callMe(){
...
}
}
如果没有,您可以使用ref使其起作用。
您可能需要: https : //facebook.github.io/react/docs/refs-and-the-dom.html
这取决于您的组件之间如何相互关联。 如果一个是父母,另一个是孩子,则该函数可以作为道具从父母传递给孩子,例如
class Parent extends React.Component {
callMe() {
console.log('called');
}
render() {
return (
<Child doSomething={() => this.callMe()} />
);
}
}
class Child extends React.Component {
render() {
<button onClick={this.props.doSomething}>Calls the parent fn</button>
}
}
或者,如果它们不是父子关系,则需要引入一个父组件,函数可以在其中生活,然后以相同的方式通过道具传递该组件。
如果这两种方法都不适合,那么请让我们知道您想要实现的行为需要这样做,并且很可能有另一种方式来构造您的代码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.