46_RN笔记5_props和state

一,props:

注意:属性,不可用更改

1,系统组件,有自己的属性,例如

let pic={
  uri: 'http://p4.music.126.net/cq1STvQ6q5b_Eg5grsTjYQ==/3275445147663993.jpg'
};
return (
  <View style={styles.container}>
    <Image source={pic} style={{width: 200, height: 200}} />
  </View>
);

2,自定义组件也可以有属性,通过this.props来获取

//定义组件:(注意:this.props.name是any类型,具体类型由引用者来决定)
class Description extends Component{
  render() {
    return (
        <Text style={styles.welcome}>This is a picture of {this.props.name}</Text>
    );
  }
}

//使用组件
return (
  <View style={styles.container}>
    <Image source={pic} style={{width: 200, height: 200}} />
    <Description name="Taylor Swift"/>
  </View>
);

3,也可以在自定义组件里,设置默认值来使用

export default class propTypes extends Component {

    // 定义属性(类型可以不用定义,设置初始值时会去判断)
    static propTypes = {
        name:PropTypes.string,
        age:PropTypes.number
    }

    // 初始值
    static defaultProps = {
        name:'xmg',
        age:2
    }

    render() {
        console.log(this.props.string)
        return (
            <View style={}>
                 <Text>
                    {this.props.name}
                 </Text>
            </View>
        )
    }
    
}

4,特殊属性:this.props.children

用来遍历子组件,个人认为可以被...运算符取代,后续会讲到

//父组件,有3个子组件
<Swiper>
  <View style={{backgroundColor: 'red'}}/>
  <View style={{backgroundColor: 'green'}}/>
  <View style={{backgroundColor: 'blue'}}/>
</Swiper>

//利用this.props.children从父组件获取需要展示的列表项内容
//使用React.Children.map方法遍历children,逐项设置,此方法返回一个数组对象,数组中的元素是child

{
  React.Children.map(this.props.children, (child) => {
    return (
      {child}
    )
  })
}

二,state

1,用来改变组件的状态,刷新数据;

2,state是一个局部的、只能被自身控制的数据源

3,使用方法:在constructor中初始化state,然后在需要修改时调用setState方法

export default class HomeView extends Component {

//  初始化state
  constructor(props) {
    super(props);
    this.state = {isPoweron: false };
    this.onPowerClick = this.functionClick.bind(this);
  }

//  点击事件后setState方法来更新state
  functionClick() {
    this.setState({
      isPoweron: !this.state.isPoweron
    });
  }
 
 
  render() {
    return (
      <View style={this.state.isPoweron ? styles.Poweron : styles.Poweroff}>
        <TouchableOpacity
          style={styles.btnstyle}
// 触发点击事件
          onPress={this.onPowerClick}
        />
      </View>
    );
  }
 
}

4,注意:

  • 不强制:state 是可选项,不是所有组件强制拥有
  • 不用:尽可能多的组件无状态化:这样做能隔离 state,也能减少冗余,同时易于解释程序运作过程
  • 要用:有时需要对用户输入、服务器请求或者时间变化等作出响应,这时才需要使用 State

猜你喜欢

转载自blog.csdn.net/a_horse/article/details/82628315