简体   繁体   中英

How to return the component from external function using react-native

Here i am using two components,

var first = React.createClass(){
     render:function(){
          <View>
             <Text>First Component</Text>
             <TextInput style={{borderWidth:1,borderColor:'red'}} onPress={getData()}/>
          </View>
      }
})
    function getData(){
      <second/>
    }
    var second = React.createClass(){
         render:function(){
              <View>
                 <ScrollView>
                   <Text>Second component</Text>
                 </ScrollView>
              </View>
          }
    })

Required Result: First Component Second component

it looks like you're trying to show a new component when something is clicked? The way I would handle this is by using state. Generally you only want JSX to show up in your render method.

So what you should do is have something like:

var first = React.createClass({
  getInitialState: function() {
    return {
      showSecond: false
    };
  },
  _handlePress: function() {
    return this.setState(showSecond(true));
  },
  render: function() {
    <View>
      <View style={styles.first}>
        <Text> ... </Text>
        <TextInput />
        <TouchableHighlight onPress={@_handlePress}>
          <Text> Button </Text>
        </TouchableHighlight>
      </View>
      {if showSecond
        <View style={styles.second}>
          <ScrollView>
            <Text> Scroll Item </Text>
          </ScrollView>
        </View>
      }
    </View>
  }
});

Now what happens is when you press the button you change state, which rerenders your component, and now that the state is true, it shows the second component

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