[英]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.