问题
How do i load my React toolbar component conditionally on state change?
constructor(props) {
super(props);
this.state = {
currentpagenum: 0,
};
}
render(){
return(
<View>
{this.state.currentpagenum!==0 ? this.getToolbar(): null;}
</View>
);
}
getToolbar(){
return(
<ToolbarAndroid />
);
}
回答1:
Looks like you got a typo error you added ;
after null
this is unneeded also you can get rid of the getToolbar function
Instead try:
constructor(props) {
super(props);
this.state = {
currentpagenum: 0,
};
}
render() {
return(
<View>
{this.state.currentpagenum !== 0 ? <ToolbarAndroid /> : null}
</View>
);
}
回答2:
Another way to render something conditionally is to do this:
render() {
return(
<View>
{this.state.currentpagenum !== 0 && <ToolbarAndroid />}
</View>
);
}
Which of course due to how 'truthiness' works in javascript, means you could shorten that further to this:
render() {
return(
<View>
{this.state.currentpagenum && <ToolbarAndroid />}
</View>
);
}
来源:https://stackoverflow.com/questions/38615767/how-do-i-load-my-react-component-conditionally