react native自定義class組件以及組件綁定事件處理

react native自定義class組件以及組件綁定事件處理react

先新建一個toast子組件,在組件中,定義一個點擊事件,點擊事件可讓data變量自增react-native

import React, { Component } from 'react';
import { StyleSheet, Text, View, } from 'react-native';

// 組件
export default class Toast extends Component {
    constructor(props) {
        super(props);
        this.state = {
            data:1
        }
    }

    change = () => {
        this.setState({
            data:this.state.data+1
        })
    }

    render() {
        let {data} = this.state
        let {text} = this.props
        return (
            <View style={styles.container}>
                <Text onPress={() => this.change()}>Toast組件</Text>
                <Text>{text}</Text>
                <Text>{data}</Text>
            </View>
        );
    }
}


const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center'
    }
})
複製代碼

新建一個父級頁面,負責引入組件bash

import React, { Component } from 'react';
import { StyleSheet, Text, View} from 'react-native';
import Toast from '../../../components/toast/Index'  //  引入組件

// 首頁
export default class Index extends Component {
  constructor(props) {
    super(props);
    this.state = {
      text:'組件傳值'
    }
  }

  render() {
    let { list,text } = this.state
    return (
      <View style={styles.container}>
        <Toast text={text}/>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
  }
});

複製代碼

最後效果flex

效果圖
相關文章
相關標籤/搜索