组件的props属性和state状态

时间:2019-06-26
本文章向大家介绍组件的props属性和state状态,主要包括组件的props属性和state状态使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

props属性:

  我使用代码来说明React中props属性:

// Profile.jsx
import React from 'react' ;
export default Class Profile extends React.Component {
    // render 是这个组件渲染的Vitrual DOM结构
    render() {
        return (
            <div className-"profile-component">
                </*this.props就是传入的属性*/>
                <h1>my name is {this.props.name}</h1>
                <h2>my age is {this.props.age}</h2>
            </div>
        )
    }
}

用这种方式,就实现了一个React的组件,在其他的组件中,可以像HTML标签一样引用它。有了组件以后,可以使用React提供的另外一个库ReactDOM把这个组件挂载到DOM节点上。

// app.jsx
import  { render } from 'react-dom';
import Profile from './profile';
render(<Profile name="lewis" age=26 />, document.getElementById('app'));
// 或者可以使用...属性拓展
const props = {
    name: 'lewis',
    age: 26
};
render(<Profile {...props} />, document.getElementById('app'));

state状态:

  state是组件内部的属性。组件本身是一个状态机,它可以在constructor中通过this.state直接定义它的值,然后根据这此值来渲染不同的UI。当state的值发生改变时,可以通过this.setState方法让组件再次调用render方法来渲染新的UI。
//Profile.jsx
export default class Profile extends React.Component {
  constructor (props) {
    super (props);
    this.state = {
      liked: 0
    };
    this.likedCallback = this.likedCallback.bind(this);
  }
  likedCallback() {
    let liked = this.state.liked;
    liked++;
    this.setState({
      liked
    });
  }

  render() {
    return (
      <div>
        <h1>我的名字叫{this.props.name}</h1>
        <h2>我今年{this.props.age}</h2>
        <button onClick={this.likedCallback}>点赞</button>
        <h2>总点赞数:{this.state.liked}</h2>
      </div>
    )
  }
}
  和上面描述的一样,在constructor中添加this.state的定义,每次单击按钮以后调用回调函数,给当前liked值加1,然后更新this.setState完成UI的重新渲染。因为在ES6 class 类型的component组件声明方式中,不会把一些自定义的callback函数绑定到实例上,所以需要手动在constructor里面绑定。
this.likedCallback = this.likedCallback.bind(this);

原文地址:https://www.cnblogs.com/xiaojuziya/p/11094477.html