Props属性实现组件传值
Props
是properties的简写。通过Props
可以组件传值
如下例子
import React from 'react'
import { Text, View} from 'react-native'
const Cat = (props) => {
return(
<View> <Text> 这里写一些文字 {props.name} ,再来{props.text}</Text> </View>
);
}
const Cafe = () => {
return (
<View>
<Cat name="{名字}" />
<Cat text="{加一点文字}" />
<Cat name="{这个名字}" text="{这个加文字}" />
</View>
);
}
export default Cafe;

React Native很多核心组件都提供props,例如Image组件,提供了source/style等属性,用来指定显示的内容
<Image source={{uri:"https://reactnative.dev/docs/assets/p_cat1.png"}} />
State 用户交互
props用于组件渲染参数,state用于组件的数据记录。如下Class组件
import React, { Component } from "react"
import { Button, Text, View } from "react-native"
class Cat extends Component {
state = { isHungry: true };
render() {
return(
<View>
<Text> 这 {this.props.name}, 那{ this.state.isHungry ? "真饿" : "不饿"} </Text>
<Button onPress={() => { this.setState({isHungry: !this.state.isHungry})}} title={this.state.isHungry ? "我饿了,喂我" : "不想吃"}/>
</View>
)
}
}
class Cafe extends Component {
render() {
return(
<View>
<Cat name = "「名字」" />
</View>
);
}
}
export default Cafe;

不要直接给组件 state 赋值(比如this.state.hunger = false)来修改状态。使用this.setState()方法才能使 React “留意”到状态变化从而重新渲染。直接修改 state 可能使界面无法正常响应。
网友评论