美文网首页
Props、State

Props、State

作者: 大写的空气 | 来源:发表于2021-07-29 16:36 被阅读0次

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 可能使界面无法正常响应。

相关文章

网友评论

      本文标题:Props、State

      本文链接:https://www.haomeiwen.com/subject/acffvltx.html