简体   繁体   中英

React Native Conditional Rendering without if statement

Is it possible to re-render specific components without using if/else statement in the rendersection. So when a specific statement changed only his specific component(s) will re-render while the rest remain intact.

Because if I use the componentWillUpdate or shouldComponentUpdate it will re-render the whole app scene again.

I look forward to your answers.

You can try something like -

class MainComponent extends React.Component {
        displayMessage() {
            if (this.props.isGreeting) {
                return <Text> Hello, JSX! </Text>;
            } else {
                return <Text> Goodbye, JSX! </Text>;
            }
        }

        render() {
            return ( <View> { this.displayMessage() } </View> );
        }
    }

Check this article - https://medium.com/@szholdiyarov/conditional-rendering-in-react-native-286351816db4

You can try with new ES6 enhanced object litrals. We can access the property of an object using bracket [] notation:

myObj = { "name":"Stan", "age":26, "car": "Lamborghini"};
x = myObj["name"]; //x will contain Stan

So you can use this approach for conditional rendering

this.state = {
    contentToDisplay: "content1",
}

render() {
    return (
        <section>
            {{
                content1: <Content1 />,
                content2: <Content2 />,
                content3: <Content3 />,
            }[this.state.contentToDisplay]}
        </section>
    );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM