React Native props and state counter example
./index.js
import { AppRegistry } from 'react-native'; import { name as appName } from './app.json'; import App from './src/App'; AppRegistry.registerComponent(appName, () => App);
./src/Counter.js
import React from 'react'; import { Button, StyleSheet, Text } from 'react-native'; export default function Counter(props) { return ( <>{props.counter} > ); } const styles = StyleSheet.create({ counter: { margin: 10, fontSize: 24, }, });
./src/App.js
import React, { Component } from 'react'; import { StyleSheet, View } from 'react-native'; import Counter from './Counter'; export default class App extends Component { constructor() { super(); this.state = { counter: 0 }; this.handleOnClick = this.handleOnClick.bind(this); } handleOnClick() { this.setState({ counter: this.state.counter + 1 }); console.log(this.state); } render() { return (); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, });
The props for the Counter are counter and handleOnClick, the values for the props are defined and passed when it is added in the View tag in App’s render function.
The state is defined in the constructor of App, and the property of the state is counter which is passed to Counter as a prop. The value of the counter property in state is updated when handleOnClick is called. Which in turn will update the prop in Counter view.
Search within Codexpedia
Custom Search
Search the entire web
Custom Search
Related Posts