我正在使用https://reactnavigation.org/docs/navigators/tab中的TabNavigator,我希望使用state.routeName动态返回我的组件。
import React, { Component } from 'react';
import { View, Text} from 'react-native';
export default class DashboardSelectionTab extends Component {
constructor(props) {
super(props);
}
render() {
const {state} = this.props.navigation;
我在这里得到以下state.routeName,即" Day"," Week"," Month"," Custom"因此,每个标签
const Day = () => (
<Text>Day</Text>
);
const Week = () => (
<Text>Week</Text>
);
const Month = () => (
<Text>Month</Text>
);
const Custom = () => (
<Text>Custom</Text>
);
我这样做但是我遇到了语法错误。
return <{state.routeName } />
}
}
有任何帮助吗?感谢。
答案 0 :(得分:0)
像这样写:
return <div>
{this.renderComponent(state.routeName) }
</div>
renderComponent(name){
switch(name){
case 'Day': return <Day/>;
case 'Month': return <Month/>
default: <Default/>
}
}
检查工作示例:
const Day = () => (
<div>Day</div>
);
const Week = () => (
<div>Week</div>
);
const Month = () => (
<div>Month</div>
);
const Custom = () => (
<div>Custom</div>
);
class DashboardSelectionTab extends React.Component {
constructor(props) {
super(props);
this.state = {compName: 'Day'}
}
renderComponent(){
switch(this.state.compName){
case 'Day': return <Day/>;
case 'Month': return <Month/>;
case 'Week': return <Week/>;
case 'Custom': return <Custom/>
}
}
render() {
return(
<div>
{this.renderComponent() }
<br/>
<select
value={this.state.compName}
onChange={(event)=>this.setState({compName: event.target.value})}
>
<option value='Day'>Day</option>
<option value='Week'>Week</option>
<option value='Month'>Month</option>
<option value='Custom'>Custom</option>
</select>
</div>
)
}
}
ReactDOM.render(<DashboardSelectionTab/>, document.getElementById('app'))
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id='app'/>
&#13;