1、props属性
props属性用来确定组件的静态展示和配置
当我们在使用Image组件时候,使用了source属性,这个属性是一个对象,里面可以定义多种key:
<Image
source={{uri: "https://reactnative.dev/docs/assets/p_cat1.png"}}
style={{width: 200, height: 200}}
/>

一个简单的自定义组件是这么写的:
const Cat = (props) => {
return (
<View>
<Text>Hello, I am {props.name}!</Text>
</View>
);
}
const Cafe = () => {
return (
<View>
<Cat name="Maru" />
<Cat name="Jellylorum" />
<Cat name="Spot" />
</View>
);
}

改造:
const Cat = (props) => {
return (
<View>
<Text>Hello, I am {props.name.name}!</Text>
</View>
);
}
const Cafe = () => {
return (
<View>
<Cat name={{name:"1234"}} />
</View>
);
}

在 JSX 中,引用 JS 值时需要使用{}括起来
字符串不需要{}
数字、数组、对象,需要用{}
对象:
{a :"13"}
数组:
["1","13"]
数字:
1
字符串:
"123"
因此要在 JSX 中传递一个 JS 对象值的时候,就必须用到两层括号:{{width: 200, height: 200}}。
2、 state
state用户交互数据发生变化来更新组件用的
需要使用react框架的useState
import React, { useState } from "react";
const [isHungry, setIsHungry] = useState(true);
此行带代码做了2件事情:
创建一个“状态变量”,并赋予一个初始值。上面例子中的状态变量是isHungry,初始值为true。
同时创建一个函数用于设置此状态变量的值——setIsHungry。
<Button
onPress={() => {
setIsHungry(false);
}}
//..
/>
3,JSX片段
由于 JSX 的语法要求根元素必须为单个元素
<>和</>
如果我们需要在根节点处并列多个元素,就用它。
在此前不得不额外套一个没有实际用处的View
网友评论