【问题标题】:React Native Conditional Rendering without if statement没有 if 语句的反应原生条件渲染
【发布时间】:2018-05-21 23:08:49
【问题描述】:

是否可以在不使用渲染部分中的 if/else 语句的情况下重新渲染特定组件。 因此,当特定语句更改时,只有他的特定组件将重新呈现 而其余的则保持原样。

因为如果我使用 componentWillUpdate 或 shouldComponentUpdate 它将再次重新渲染整个应用场景。

期待你的回答。

【问题讨论】:

    标签: javascript android react-native rendering


    【解决方案1】:

    你可以试试 -

    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> );
            }
        }
    

    查看这篇文章 - https://medium.com/@szholdiyarov/conditional-rendering-in-react-native-286351816db4

    【讨论】:

      【解决方案2】:

      您可以尝试使用新的 ES6 增强对象字面量。 我们可以使用方括号[] 表示法访问对象的属性:

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

      所以你可以使用这种方法进行条件渲染

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

      【讨论】:

        猜你喜欢
        • 2017-06-24
        • 1970-01-01
        • 1970-01-01
        • 2018-01-25
        • 1970-01-01
        • 2021-08-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多