gpt4 book ai didi

javascript - 在另一个组件内部调用一个组件的方法

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

我是 React Native 的新手。我有两个组件(屏幕 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 的方法,但是,它向我显示了错误“

Cannot read properity '_showModalHistory' of undefine".

您能检查一下我的代码有什么问题吗?我应该添加任何内容来执行引用吗?

最佳答案

您需要首先在 A 内渲染 B 组件。然后如下所示设置 ref。

 class A extends Component {

// Some on click listener.

onClick() {
this.B._showModalHistory();
}


render() {
return (
<B ref={component => { this.B = component; }} />
);
}
}

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

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