[英]Call the method of a component inside another component
我是本機反應的新手。 我有兩個組件(屏幕A和屏幕B),如下所示。 我需要在屏幕A內調用屏幕B的_showModalHistory
方法。這是屏幕A(組件A)的代碼:
import B from './B.js';
class A extends Component {
render() {
return (
this.refs.B._showModalHistory();
);
}
}
在屏幕B(組件B)中,我還有以下代碼:
export default class B extends Component {
constructor(props) {
super();
this.subscription = 0;
this.state = {
};
changePage = props.cb;
this.state = {
isModalVisible: false,
isModalVisibleHistory: false,
};
}
_showModalHistory = () => this.setState({ isModalVisibleHistory: true });
render() {
return (
<Modal isVisible={this.state.isModalVisibleHistory}>
<View style={styles.contianer}>
<History></History>
</View>
</Modal>
);}
}
我嘗試在屏幕A中使用ref,以達到屏幕B的方法,但是,它向我顯示了“
無法讀取未定義的屬性'_showModalHistory'。
您能檢查一下我的代碼有什么問題嗎? 我應該添加任何東西來執行裁判嗎?
您需要首先在A
內渲染B
組件。 然后如下所示設置參考。
class A extends Component {
// Some on click listener.
onClick() {
this.B._showModalHistory();
}
render() {
return (
<B ref={component => { this.B = component; }} />
);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.