您可能应该将 React 组件视为一棵树,并且您可以将要触发的函数从父级传递给子级作为道具。
假设你有一个 Tab 组件 -
const Tab = React.createClass({
onPressButton(){
triggeredFunction();
},
render() {
return (
<Button onPress={this.onPressButton}>
<Text>Press Me!</Text>
</Button>
);
},
});
如果你想模拟触摸,你可以简单地调用triggeredFunction()(或在组件中this.onPressButton)。
如果您尝试从父组件触发函数,您可能应该在父组件中拥有触发函数并将其作为 prop 传递 -
const Tab = React.createClass({
propTypes: {
onPressButton: React.PropTypes.func,
tabNumber: React.PropTypes.number,
tabText: React.PropTypes.string,
},
triggerTheTriggerToTrigger() {
// This will trigger the triggeredFunction in the page component and pass in the tab number
// Remember that onPressButton={this.triggeredFunction}
// So you are calling this.triggeredFunction(tabNumber) in the parent page component
this.props.onPressButton(this.props.tabNumber);
},
render() {
return (
<Button onPress={this.triggerTheTriggerToTrigger}>
<Text>{this.props.tabText}</Text>
</Button>
);
},
});
然后在你的主要组件中
const Page = React.createClass({
getInitialState() {
return {
currentTab: 1,
};
},
triggeredFunction(tabNum) {
// This function is setting the state of the page component to be equal to that passed from the tab
// So when the tab is touched it will trigger the page to change to that number.
this.setState({
currentTab: tabNum,
});
},
// main component render:
render() {
let content;
// We are setting the page 'content' from here
// Choosing the content from the currentTab state
switch (this.state.currentTab) {
case 1:
content = <Text>This is the content for tab 1</Text>
break
case 2:
content = <Text>Tab 2 has a slightly different message</Text>
break
case 3:
content = <Text>Tab 3 is slightly different too</Text>
break
}
return (
<View className="page">
<View className="toptabs">
<Tab onPressButton={this.triggeredFunction} tabText="Button 1" tabNumber={1} />
<Tab onPressButton={this.triggeredFunction} tabText="Button 2" tabNumber={2} />
<Tab onPressButton={this.triggeredFunction} tabText="Button 3" tabNumber={3} />
</View>
<View className="pageContent">
{content}
</View>
</View>
);
},
});
然后您可以改为从主组件调用this.triggeredFunction()。我希望这是有道理的。
我还没有测试过这段代码,所以它可能需要一些调整,但希望它能向你展示它背后的逻辑。
另外,我在这里使用了一个 switch 语句来使正在发生的事情变得明显。我可能不会在真正的应用程序中使用这种方法(并不是说它特别糟糕)。您还可以加载其他组件并根据 currentTab 状态有条件地加载它们。您可以创建一个内容数组并拥有 -
let content = contents[this.state.currentTab];
您也可以通过其他方式实现此目的。我在我的应用程序中使用了通量,其中包含您更新的商店。这些存储然后用数据传播视图。这意味着您可以获得更多的全局设置。如果您使用的是flux,那么您基本上可以从flux中设置页面状态(即tabNumber)。
因此,在您的标签中,您可以将 onPressButton 设置为 -
this.flux.action.updateTab(this.props.tabNumber);
这将更新全局存储以设置您所在的 tabNumber(即您不再只是在页面组件上设置 currentTab)
在您的页面中,您可以通过以下方式获取 currentTab 状态 -
currentTab: this.flux.store.tabStore.getCurrentTab()
所以商店会在更新时更新您的页面组件。
但这是一个比您使用的更复杂的实现,它超出了我们在这里讨论的范围。如果该部分令人困惑,请不要担心,但如果您将来要构建更大的东西,考虑它可能会有所帮助(想象一下 10 个不同的应用程序“页面”,其中包含用于不同事物的选项卡部分,突然间您想要一个存储空间可以控制它们的状态,而不是在每组组件中)。