Home > OS >  Calling a function through React Component
Calling a function through React Component

Time:06-24

The function add is not being rendered. The text inside the function add not appearing when the button in the render method is clicked. Feel this is one of those issues with what 'this' is bound too, what do y'all think?

import {Button, StyleSheet, Text, View } from 'react-native'

import React from 'react'

export default class App extends React.Component
{
    constructor() {
        super()
    }

    add () {
      return(
        <Text>Hi</Text>
    )}

    render(){
      return(
        <View styles={styles.button}>
            <Text> Set Timer </Text>
            <Button onPress={this.add} title="Hey there"/>
        </View>
      )
    }

}



const styles = StyleSheet.create({
  button: {
    width: 10,
    height: 10,
  }

});

CodePudding user response:

If your goal is to change the output of the render method, this won't work. The output of the add function won't affect the render method at all - it will return the JSX to the button, which won't do anything with it.

One way to change the output of the render method is to have it depend on internal state. Something like the following is a common pattern. I'm not sure what your use case is since this seems like demo code, but maybe this solution will work for you.

    constructor() {
        super()
        this.state = { add: false }
    }

    add() {
        this.setState({ add: true });    
    }

    render() {
      return(
        <View styles={styles.button}>
            {this.state.add ? <Text>Hi</Text> : <Text> Set Timer </Text>}
            <Button onPress={this.add} title="Hey there"/>
        </View>
      )
    }

CodePudding user response:

Another note to is to make sure you are binding your function in the constructor so the class knows which function to refer to through 'this'. You can also eliminate this code by using an ES6 function. Example below.

Using bind:

  constructor() {
        super()
        this.state = { add: false }
        this.add = this.add.bind(this);
    }

    add() {
        this.setState({ add: true });    
    }

    render() {
      return(
        <View styles={styles.button}>
            {this.state.add ? <Text>Hi</Text> : <Text> Set Timer </Text>}
            <Button onPress={this.add} title="Hey there"/>
        </View>
      )
    }

Using an ES6 function:

  constructor() {
        super()
        this.state = { add: false }
    }

    add = () => {
        this.setState({ add: true });    
    }

    render() {
      return(
        <View styles={styles.button}>
            {this.state.add ? <Text>Hi</Text> : <Text> Set Timer </Text>}
            <Button onPress={this.add} title="Hey there"/>
        </View>
      )
    }

  • Related