【发布时间】:2018-04-27 06:35:36
【问题描述】:
我必须在组件 A 中调用组件 B 中的一些方法。 这是组件B:(如果您需要更多代码,请向我索取,我会更新我的帖子)
import A from "./A";
export default class B extends Component {
componentDidUpdate (prevProps, prevState) {
this.props.onRef(this);
}
renderContent ( ) {
let toolbarActiveItem = Toolbar.getActiveItem();
if (Toolbar.getActiveItem()=="XXXX") {
this.refs.A._showModalHistory();
} else {
toolbarActiveItem = Toolbar.getActiveItem();
}
return (
<Container>
{(toolbarActiveItem == 'YYY') && <C navigation={this.props.navigation} cb={this.childCallback} info={this.props.navigation.state.params}/> }
</Container>
);
}
render () {
return (
<StyleProvider style={getTheme(Config.theme)}>
<A ref={component => { this.A = component; }} />
<Container ref={this.ref}>
{ this.renderNavbar(this.title) }
{ this.renderToolbar() }
{ this.renderContent() }
{ this.renderDialog() }
</Container>
</StyleProvider>
);
}
这是组件 A:
export default class A extends Component {
constructor(props) {
super();
this.subscription = 0;
this.state = {};
changePage = props.cb;
this.state = {
isModalVisibleHistory: false,
};
}
_showModalHistory = () => this.setState({ isModalVisibleHistory: true });
render() {
return (
<Modal isVisible={this.state.isModalVisibleHistory}>
<View style={styles.BG}>
<ParkHistory></ParkHistory>
</View>
</Modal>
);
}
}
我的问题是,我需要在组件 B 中执行 this.refs.A._showModalHistory(); 但是,我看到以下错误:
React.Children.only 期望接收单个 React 元素子元素。
我认为,我在处理渲染多个组件并引用它们时遇到了问题。我应该提一下,当我删除 <A ref={component => { this.A = component; }} /> 时,我的代码可以正常工作,但是没有调用该方法。你能帮我解决这个问题吗?
【问题讨论】: