reactjs - 如何将道具从一个组件传递到另一个组件?(反应原生)
问题描述
我有一个用于选项卡视图的自定义组件,通过它我可以制作动态选项卡,下面是它的代码。
TabView
是制作这些自定义选项卡的自定义,并且Selected
是单个选项卡的组件。
如何将道具从TabView
组件发送到Selected
组件?
我知道如何在常规场景中发送道具,但我不知道在这种情况下发送道具。
我从以下链接制作了这个组件:
export class TabView extends Component {
Tabs = navigation => {
let tabs=['A', 'B', 'C', 'D','E','F','G','H'];
tabs = tabs.reduce((val, tab) => {
val[tab] = {
screen: Selected
}
return val
}, {})
const bottomTabs = createMaterialTopTabNavigator(
{
...tabs
},
{
tabBarOptions: {
style: {
backgroundColor: Themes.colors.FC_PRIMARY,
},
indicatorStyle:{
height: 2,
backgroundColor: Themes.colors.TC_PRIMARY_LIGHT,
},
}
}
)
const Tabs = createAppContainer(bottomTabs);
return <Tabs />
}
render() {
const { navigation } = this.props;
return (
<View style={STYLES.tabView}>
{this.Tabs(navigation)}
</View>
);
}
}
export class Selected extends Component {
constructor(props){
super(props);
this.state = {
screen: '',
screenType: this.props.type
}
}
static navigationOptions = ({ navigation }) => {
return({
tabBarLabel: ({ focused }) => (
<View>
<View style={STYLES.secondaryTabLabel}>
<H3
type={ focused ? "light" : "disabled" }
text={navigation.state.routeName}
/>
</View>
</View>
)
})
};
screenIs = payload => {
this.setState({ screen: payload.state.routeName })
}
render() {
const { navigation } = this.props;
return (
<View style={{flex: 1}}>
<NavigationEvents onWillFocus={this.screenIs} />
<Text>{this.state.screen}</Text>
</View>
);
}
}
解决方案
使用以下代码,
val[tab] = {
screen: () => (<Selected val={val}/>) //in case if you want to send val as props
}
所以你的最终代码将是,
export class TabView extends Component {
Tabs = navigation => {
let tabs=['A', 'B', 'C', 'D','E','F','G','H'];
tabs = tabs.reduce((val, tab) => {
val[tab] = {
screen: () => (<Selected val={val}/>), // for props
navigationOptions: {
title: 'Shows' // send anything here to get in navigationOptions
},
}
return val
}, {})
const bottomTabs = createMaterialTopTabNavigator(
{
...tabs
},
{
tabBarOptions: {
style: {
backgroundColor: Themes.colors.FC_PRIMARY,
},
indicatorStyle:{
height: 2,
backgroundColor: Themes.colors.TC_PRIMARY_LIGHT,
},
}
}
)
const Tabs = createAppContainer(bottomTabs);
return <Tabs />
}
render() {
const { navigation } = this.props;
return (
<View style={STYLES.tabView}>
{this.Tabs(navigation)}
</View>
);
}
}
export class Selected extends Component {
constructor(props){
super(props);
this.state = {
screen: '',
screenType: this.props.type
}
}
static navigationOptions = ({ navigation, navigationOptions }) => {
return({
tabBarLabel: ({ focused }) => (
<View>
<View style={STYLES.secondaryTabLabel}>
<H3
type={ focused ? "light" : "disabled" }
text={navigationOptions.title} // use here
/>
</View>
</View>
)
})
};
screenIs = payload => {
this.setState({ screen: payload.state.routeName })
}
render() {
const { navigation } = this.props;
return (
<View style={{flex: 1}}>
<NavigationEvents onWillFocus={this.screenIs} />
<Text>{this.state.screen}</Text>
</View>
);
}
}