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

效果图
相关文章
相关标签/搜索