我有这个结构,其中有一个 MyComponent
列表:
class MyComponent extends Component
{
props: { navigation: Object, data: Object };
ShowScreenB(data: Object){
this.props.navigation.navigate('ScreenB', {data});
}
render()
{
return (
<Menu>
<MenuTrigger> <Text> Menu </Text> </MenuTrigger>
<MenuOptions>
<MenuOption onSelect={() => this.ShowScreenB.bind(this, this.props.data)} text='Show Screen B' />
</MenuOptions>
</Menu>
);
}
}
class MyScreen extends Component
{
render()
{
let renderRow = (row) => { return (<MyComponent data= {row} navigation= {this.props.navigation} /> );}
return (
<View >
<ListView dataSource={this.state.DataSource} renderRow={renderRow.bind(this)}/>
</View>
);
}
}
但是 ShowScreenB()
不会转到另一个屏幕。
我还尝试在 MyScreen
类中准备导航器,然后将其作为函数传递给 MyComponent
。但也不起作用:
class MyComponent extends Component
{
props: { OnPress: Function, data: Object };
render()
{
return (
<Menu>
<MenuTrigger> <Text> Menu </Text> </MenuTrigger>
<MenuOptions>
<MenuOption onSelect={() => this.OnPress.bind(this)} text='Show Screen B' />
</MenuOptions>
</Menu>
);
}
}
class MyScreen extends Component
{
ShowScreenB(data: Object){
this.props.navigation.navigate('ScreenB', {data});
}
render()
{
let renderRow = (row) => { return (<MyComponent data= {row} OnPress= {this.ShowScreenB.bind(this, row)} /> );}
return (
<View >
<ListView dataSource={this.state.DataSource} renderRow={renderRow.bind(this)}/>
</View>
);
}
}
可能是什么问题?
编辑:菜单
是PopUp Menu .
最佳答案
你永远不会调用ShowScreenB()
。
现在您只需绑定(bind)它:
onSelect={() => this.ShowScreenB.bind(this, this.props.data)}
bind不调用该函数。它所做的一切都是将其绑定(bind)到给定的上下文。您需要实际调用 ShowScreenB()
以便执行导航代码。例如:
onSelect={() => { this.ShowScreenB.bind(this); this.ShowScreenB(this.props.data); }}
编辑以回答评论,因为它不适合评论:
这是因为删除 ( ) =>
使得您所拥有的只是剩下的 { }
语法。 { }
表示计算括号内的内容。看看我的答案链接中写的内容。 bind
的返回值为:
A copy of the given function with the specified this value and initial arguments.
因此表达式 { this.ShowScreenB.bind(this) }
将计算返回值;因此调用导航功能。我上面发布的内容只是您可以执行的操作之一。您也可以将其编写为 onSelect={() => this.ShowScreenB.bind(this)()}
并且它也可以工作。如果您遇到此问题,您还应该温习一下如何 arrow functions工作。
关于javascript - 为什么我的导航器不工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45064172/