Programmatically add a component in React Native

后端 未结 4 1635
忘掉有多难
忘掉有多难 2020-12-09 04:35

Suppose I have a simple React Native app like so:

\'use strict\';

var React = require(\'react-native\');
var {
  AppRegistry,
  Text,
  TouchableHighlight,
         


        
4条回答
  •  被撕碎了的回忆
    2020-12-09 05:15

    In react or react native the way component hide/show or add/remove does not work like in android or iOS. Most of us think there would be the similar stratedgy like

    View.hide = true or parentView.addSubView(childView

    But the way react native work is completely different. The only way to acheive this kind of functionality is to include your component in your DOM or remove from DOM.

    Here in this example I am going set the visibility of text view based on the button click.

    enter image description here

    The idea behind this task is the create a state variable called state having the initial value set to false when the button click event happens then it value toggles. Now we will use this state variable during the creation of component.

    import renderIf from './renderIf'
    
    class fetchsample extends Component {
      constructor(){
        super();
        this.state ={
          status:false
        }
      }
      toggleStatus(){
    
      this.setState({
        status:!this.state.status
      });
      console.log('toggle button handler: '+ this.state.status);
      }
    
      render() {
        return (
          
           {renderIf(this.state.status)(
             
             I am dynamic text View
             
           )}
    
            this.toggleStatus()}>
               touchme 
            
          
        );
      }
    }
    

    the only one thing to notice in this snippet is renderIf which is actually a function which will return the component passed to it based on the boolean value passed to it.

    renderIf(predicate)(element).

    renderif.js

    'use strict';
    const isFunction = input => typeof input === 'function';
    export default predicate => elemOrThunk =>
      predicate ? (isFunction(elemOrThunk) ? elemOrThunk() : elemOrThunk) : null;
    

提交回复
热议问题