react-native 简单入门语法
语法
RN的语法与vue类似,我们有过vue基础的话入手比较简单,但是没有vue基础也能快速掌握
1.{} 插值表达式
代码如下(示例):
import React from "react";
import { View, Text, Dimensions, TouchableOpacity, Image } from 'react-native';
const Index=()=>
<View>
<Text>
{"我是插值语法"}
</Text>
</View>
注意:如果我们要向vue一样去操作数据,可以想和这样
import React from "react";
import { View, Text, Dimensions, TouchableOpacity, Image } from 'react-native';
const Index=()=>
<View>
<Text>{"我是插值语法"}</Text> //这里用{}表示插值语法
</View>
//入过我们要操作对象和数组的话
const obj = { name: "李四" } //定义一个对象
const arr=["张三","李四","王五"] //定义一个数组
const Index = () =>
<View>
<Text> {"我是插值语法"}</Text>
{/* 这是操作对象 */}
<Text>{obj.name}</Text>
{/* 这是操作数组,注意数组一般我们是进行循环,这里的循环我们一般使用的是数组的map方法 */}
{arr.map( (item,index)=><View key={index} style={{backgroundColor:"yellow"}}>
<Text>{item}---</Text>
</View>)
}
</View>
提示:
我们要记住{}就是类似于在标签中写js代码的地方
2.组件的形式
类组件:
代码如下(示例):
import React from "react";
import { View, Text, Dimensions, TouchableOpacity, Image, YellowBox } from 'react-native';
//定义一个类组件,必须继承Reaact.Component
calss Father extends React.Component{
//我们要使用state时,我们可以这样来
state={
num:100
},
//组件挂载完毕的生命周期
componentDidMount(){}
render(){
return
//如果我们要修改state里面数据,我们要使用set方法,直接修改是错误的 this.state.num=1000(×)
this.setState({
num:1900
})
<View>
<Text>hahahh~</Text>
//我们要使用state里面的数据
<Text>{this.atate.num}</Text>
</View>
}
}
export default Father;
2.组件的属性props
我门使用peops的时候可以进行给子组件传递数据,用于父子组件通讯
代码如下(示例):
import React from "react";
import { View, Text, Dimensions, TouchableOpacity, Image } from 'react-native';
// 1 定义一个父组件
const Father=()=>
<View>
<Text>我是父组件里面的数据</Text>
// 3 在父组件中使用子组件
// 4 如果我们要传递数据给子组件的话我门可以这样来 定义传递数据 color="red"
<Sub color="red" >
// 9 插槽的使用
<View><Text>我是通过插槽显示在Sub组件文字的下面</Text></View>
</Sub>
</View>
//2 定义一个子组件
//5我们在父组件理通过 color="red"传递过来的数据,我们子组件这样使用props来传递,(props)=>{}
//6在子组件中使用数据
//7 插槽使用:就比如我拿Sub来做,我希望在子组件里面写一些标签,把标签的内容显示在子组件文字的下面
const Sub=(props)=>
<View>
<Text>我是子组件</Text>
<Text style={{color:props·color}} >显示父组件传递过来的数据{props·color}</Text>
// 8 在Sub中定义一个插槽 props.children
{props.children}
</View>
总结
1 {}语法:
这个就跟vue里面的一样的意思,就类似于在{}里面的我们可以写js代码。主语我们一般写style={{}},这里是两个{{}},如果我们要写一个标签上的一个属性, 比如Image的属性source,属性值一般要写一个{}。source={}。还有一些属性比较复杂,比如transition属性,他可能有多个属性值,我们要向这样写transform:[{translateY:300},{scale:2}
2 类组件
语法 class XXX ectends React.Component {
state={}, //定义一个state
componentDidMount(){} , //组件挂载完毕的生命周期
render(){ //必须写render方法
return
}
}
3 插槽