![](/img/trans.png)
[英]ReactJS how to call a component function from another function on the same file?
[英]How to call function from another component in reactJs
在reactJs中,我有两个文件,其中一个具有实用程序功能,另一个文件我想要使用这些功能。
像一个例子:
file1.js
import React, {Component} from 'react';
class CloseableTab extends Component {
constructor() {
super();
this.state = tabs;
this.addItem = (link) => {
this.setState({
activeIndex: this.state.data.length
});
};
}
}
export default CloseableTab
因此,在上面的代码中,您可以看到我在CloseableTab类中具有名为“ addItem”的函数或方法。 [其中包含我想在另一个文件中使用的功能。]
File2.js
import React, {Component} from 'react';
import CloseableTabs from '../../containers/CloseableTab/CloseableTab';
class ProductList extends Component {
this.appendItem = (item) => {
addItems(item); //here i want to use the functionality method.
};
}
export default ProductList
因此,在上面的file2.js中,我用参数项调用了addItems,我知道这是不正确的技术。 因此需要帮助。
是否想知道在onClick / onClick函数中如何将功能方法[file1的addItem()从file1调用到file2中?
非常感谢您的回答,谢谢。
您需要将状态提升为一位共同祖先:
class Parent extends React.Component {
constructor() {
super();
this.state = tabs;
this.addItem = (link) => {
this.setState({
activeIndex: this.state.data.length
});
};
}
render() {
return (
<div>
<CloseableTab tabs={this.state.tabs} addItem={this.addItem} />
<ProductList tabs={this.state.tabs} addItem={this.addItem} />
</div>
)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.