为什么要学react,因为在公司要写rn,发现好多属性都不熟,写起来,还是很恼火;
1.父组件调用子组件以及父子组件之间通信的方法:(和vue的一模一样);
// 父组件
class Home extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<Main // 子组件
ref='childrenComponnent' // 想给子组件取个名字
aa={1} // 这是父组件向子组件传递的数据
bb={2}
transformData={(value)=>this.transformData(value)} // 传递的是:作用域为父组件自身的函数
>
</Main> // 和vue调用一样的
<button onClick={() => this.refs.childrenComponnent.add()}>我正在调用子组件的方法</button>
</div>
);
}
transformData(value){ // 子组件向父组件传值 也是要父组件向子组件通过props传值,不过这次穿的是一个函数,然后子组件接受到了,返回一个参数,然后父组件就直接接受到了组件的传值;
console.log(value); // 获取到了 =====》:我是子组件,我正在向父组件传值
}
}
class Main extends React.Component {
render() {
console.log(this.props) // 这就是子组件获取的所有的内容了
this.props.transformData('我是子组件,我正在向父组件传值');
return (
<div>
2323
{this.props.aa}
<Sun {...this.props} /> 这是孙子组件 ... 运算符(Object 剩余和展开属性)
<button onClick={() => this.props.transformData('我是子组件,我正在调用父组件的方法')}>我是子组件,我正在调用父组件的函数</button> // 这是子组件调用父组件的方法:
</div>
);
}
add(){
console.log('我是子组件的,我正在被父组件调用呢');
}
}
class Sun extends React.Component{
render(){
console.log(this.props);
return (
<div>
<h3>我是孙子组件</h3>
<p>{this.props.aa}</p> // 还是可以获取到1的值
</div>
)
}
}
2018.11.16
react-native 总结:
把alert作为一个组件使用;
父组件:
import React, { Component } from 'react';
import { View, Text, StyleSheet, Dimensions, BackHandler, Platform, } from 'react-native'
import TopHeader, { leftBtn, rightBtn } from '../../../../../components/header/TopHeader'
import ScrollableTabView, {DefaultTabBar,ScrollableTabBar} from 'react-native-scrollable-tab-view'; // tab切换
import { Assets, AssetsAlertDialog } from './subjectInitialHomepageChild/Assets'
/**
* 首页
*/
export default class SubjectInitialHomepage extends Component {
constructor(props) {
super(props)
this.state = {
}
}
async componentWillMount(){
this.goBack();
}
goBack(){
// 监听安卓返回事件
BackHandler.addEventListener('hardwareBackPress', () => {
this.props.navigation.state.params.goBack();
this.props.navigation.goBack(null);
return true;
});
}
render() {
return (
<View style={styles.container}>
<TopHeader
ref={'topHeader'}
title={'首页'}
leftBtn={leftBtn.BACK}
navigation={this.props.navigation}
backPath={null}
/>
<ScrollableTabView
renderTabBar={() =>
<DefaultTabBar style={{ borderBottomWidth : 0, height : 50 }}/>
}
tabBarUnderlineStyle={{ backgroundColor : '#4fdf7a', height : 1, width : SCREEN_WIDTH * 0.2, marginBottom : 10 }}
tabBarActiveTextColor={'#4fdf7a'}
tabBarTextStyle={{ fontSize : 13 }}
tabBarInactiveTextColor={'#999999'}
style={{ height : SCREEN_HEIGHT, zIndex : 2 }}
onChangeTab={(obj) =>{
// console.log(obj);
}}
>
<View tabLabel={'资产'} style={{ marginTop : 0, backgroundColor : '#FAFAFA'}}>
<Assets
navigation={this.props.navigation}
ref={'assets'}
showAlert={() => { this.refs['AssetsalertDialog'].refs['alertDialog'].show() }} // 第三步: 然后父组件收到该函数,就执行该函数,然后去调用alert组件的,调用他的show方法;然后那个alert选择框就出现了;
>
</Assets>
</View>
</View>
</ScrollableTabView>
<AssetsAlertDialog
ref={'AssetsalertDialog'}
onPress={async (data) => {
await this.refs['assets'].confirmDetale(); // 第五步:收到了子组件传的值,就去调用上一个子组件函数(确认删除按钮);然后整个流程就结束了;完美!!!!!
}}
>
</AssetsAlertDialog>
</View>
);
}
componentWillUnmount() {
if (Platform.OS === 'android') {
BackHandler.removeEventListener('hardwareBackPress',()=>{});
}
}
}
1.assets 组件的
<TouchableHighlight
onPress={() => this.deleteSubjext(item)}
underlayColor={'transparent'}
activeOpacity={0.5}>
<Text style={{ color : '#f55353',fontSize: 12 }}>删除</Text>
</TouchableHighlight>
deleteSubjext(item){
this.setState({deleteId : item.accsubjid}); // 第一步: 首先把删除的id用一个值来保存着
this.props.showAlert && this.props.showAlert(); // 第二步: 然后子组件向父组件传值(react传就是一个带有父组件作用域的函数)
}
alert组件:
export class AssetsAlertDialog extends Component {
constructor(props) {
super(props)
this.state = {
}
}
render() {
return (
<View style={{ width: SCREEN_WIDTH, height: SCREEN_HEIGHT, position: 'absolute' }}>
<AlertDialog
messageText={'确定要删除吗?'}
negativeText={'取消'}
positiveText={'确定'}
onPress={(data) => data ? this.props.onPress && this.props.onPress({'ref' : 'alertDialog'}) : null} // 第四步: 如果按的第一个确定按钮,就把当前这个函数(onPress)传到父组件去
ref={'alertDialog'}
>
</AlertDialog>
</View>
)
}
}
第二大部分:
import React, { Component } from 'react';
import { View, Text, StyleSheet, Dimensions, BackHandler, Platform, TouchableHighlight,FlatList,Image } from 'react-native'
import { FormInput} from 'react-native-elements'
import { institutionalAccount, accountInitialBalance ,deleteAccsubj,saveBalance } from './../../../../../../service/getYongyouData'
import { getToast } from './../../../../../../utils/util'
import { AlertDialog } from 'huangge-react-native-pickers';
import { scaleSize } from '../../../../../../utils/screenUtil'
const SCREEN_WIDTH = Dimensions.get('window').width;
const SCREEN_HEIGHT = Dimensions.get('window').height;
/**
*资产
*/
export class Assets extends Component {
constructor(props) {
super(props)
this.state = {
}
}
async componentWillMount(){
this.goBack();
this.getinstitutionalAccount();
}
goBack(){
// 监听安卓返回事件
BackHandler.addEventListener('hardwareBackPress', () => {
this.props.navigation.state.params.goBack();
this.props.navigation.goBack(null);
return true;
});
}
async getInitialBalance(){ // 初始余额
this.setState({ loading : true });
let result = await accountInitialBalance({year : this.state.year,accsubjtype : 1});
if(result.code === 200){
for (item of result.message){
item.openingBalance = ''; // 期初余额
item.accumulatedDebit = ''; // 本年累计借方
item.cumulativeCredit = ''; // 本年累计贷方
item.initialBalance = ''; // 年初余额
}
this.setState({assetsData : result.message});
this.setState({ loading : false });
}else{
getToast(false,result.message,500);
}
}
// 上拉刷新
async onRefresh(){
// 上拉刷新 页数默认为1
this.setState({ loading : true });
await this.getInitialBalance()
this.setState({ loading : false });
}
render() {
return (
<View style={styles.container}>
{/* 解决滚动不到最后一个元素*/}
<View style={{height : SCREEN_HEIGHT*0.78}}>
<FlatList
data={ this.state.assetsData} // 获取了数据源
renderItem={({item,index}) => this.renderItem(item,index)} // 做循环处理数据的地方
onRefresh={async ()=> { await this.onRefresh() }} // 刷新
refreshing={ this.state.loading }
// 空布局
ListEmptyComponent={ this.renderEmpty() }
/>
</View>
<View style={{ height: 300, width : SCREEN_WIDTH, justifyContent : 'center', alignItems : 'center', position : 'absolute', bottom : 0 }}>
<TouchableHighlight
onPress={() => this.addEarlyStage()}
underlayColor={'transparent'}
activeOpacity={0.5}>
<Image source={require('./../../../../../../images/icon/ic_yuantianjia.png')}></Image>
</TouchableHighlight>
</View>
</View>
);
}
// 当列表为空时渲染的内容
renderEmpty(){
return <View style={{ justifyContent : 'center', alignItems : 'center', height : SCREEN_HEIGHT * 0.6 }}>
<Text style={{ color : '#CCCCCC', fontSize : 16, marginBottom : 30 }}>暂无数据!</Text>
<Image
source={require('./../../../../../../images/icon/ic_wushuju.png')}
style={{ width : scaleSize(600), height : scaleSize(320) }}
resizeMode={'stretch'}></Image>
<TouchableHighlight
onPress={async () => { await this.onRefresh() }}
underlayColor={'transparent'}
activeOpacity={0.5}>
<View style={{
marginTop : 30,
flexDirection : 'row',
width : 100,
height : 40,
borderRadius : 5,
borderWidth : 1,
borderColor : '#96D9F8',
justifyContent : 'center',
alignItems : 'center' }}>
<Image source={require('./../../../../../../images/icon/ic_shuaxin.png')} style={{ marginRight : 10 }}></Image>
<Text style={{ color : '#0ea9f3', fontSize : 16 }}>刷新</Text>
</View>
</TouchableHighlight>
</View>;
}
renderItem(item,index){
// 这里面写对数据的处理
return <View style={styles.items} key={index}> // 这个return 后面一定要写一个View 否则报错
{/* 科目编码 */}
<View style={styles.code}>
<View style={{height: 22,backgroundColor: '#17d0fb',alignItems: 'center',justifyContent: 'center'}}>
<Text style={{color: '#FFFFFF',fontSize: 12}}>科目编码</Text>
</View>
<View style={{height: 41,backgroundColor: '#FFFFFF',alignItems: 'center',justifyContent: 'center',}}>
<FormInput
keyboardType='numeric'
onBlur={() => this.saveBalance(item)}
defaultValue={item.openingBalance}
selectionColor="#0ea9f3"
underlineColorAndroid={'transparent'}
inputStyle={{textAlign: 'center',height: 40, width : SCREEN_WIDTH * 0.19, color : 'black', fontSize : 12 }}
containerStyle={{ width : SCREEN_WIDTH * 0.19}}
placeholder={'请输入'}
onChangeText={ (text) => {
var assetsData = this.state.assetsData;
assetsData[index].yb_totalc = text;
this.setState({temp : text});
}}>
</FormInput>
</View>
</View>
<View style={styles.operating}>
<View style={{height: 22,backgroundColor: '#17d0fb',alignItems: 'center',justifyContent: 'center'}}>
<Text style={{color: '#FFFFFF',fontSize: 12}}>操作</Text>
</View>
<View style={{ flexDirection : 'column', justifyContent: 'space-around', alignItems: 'center',height: 100, }}>
<TouchableHighlight
onPress={() =>this.addSubject(item)}
underlayColor={'transparent'}
activeOpacity={0.5}>
<Text style={{ color : '#5de9a7',fontSize: 12 }}>新增</Text>
</TouchableHighlight>
<TouchableHighlight
onPress ={() =>this.editSubject(item)}
underlayColor={'transparent'}
activeOpacity={0.5}>
<Text style={{ color : '#1eaaff',fontSize: 12 }}>修改</Text>
</TouchableHighlight>
<TouchableHighlight
onPress={() => this.deleteSubjext(item)}
underlayColor={'transparent'}
activeOpacity={0.5}>
<Text style={{ color : '#f55353',fontSize: 12 }}>删除</Text>
</TouchableHighlight>
</View>
</View>
</View>
}
componentWillUnmount() {
if (Platform.OS === 'android') {
BackHandler.removeEventListener('hardwareBackPress',()=>{});
this.timer && clearTimeout(this.timer);
}
}
}