Skip to content Skip to sidebar Skip to footer

React Js Pass A Function This.state Context

I have the following function in a file: helpers.js: export const returnStateElement = (...elements) => { console.log('returnStateElement',this,elements) const copy = Object

Solution 1:

You need to bind the context to the function. Here is a working snack showing how you might do that in the constructor

https://snack.expo.io/Sy8J3fyGL

And the code

import * asReactfrom'react';
import {Button, TouchableOpacity, Text, View, StyleSheet } from'react-native';

constreturnStateElement = (currentState, ...elements) => {
  const copy = Object.assign({}, currentState);
  return elements.reduce((obj, key) => ({ ...obj, [key]: copy[key] }), {});
};

exportdefaultclassAppextendsReact.Component {
  constructor(props) {
    super(props)
    this.state = {
      email: 'test@test.com'
    }

    this.returnStateElement = (...elements) =>returnStateElement(this.state, ...elements);
  }

  render() {
    return (
      <Viewstyle={styles.container}><TouchableOpacityonPress={() => alert(JSON.stringify(this.returnStateElement('email', 'pass')))}>
       <Textstyle={styles.paragraph}>Press here</Text></TouchableOpacity></View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    backgroundColor: '#ecf0f1',
    padding: 8,
  },
  paragraph: {
    margin: 24,
    fontSize: 18,
    fontWeight: 'bold',
    textAlign: 'center',
  },
});

Post a Comment for "React Js Pass A Function This.state Context"