React中的props和state

一、props

react中的prop是从外部传递给组件的数据。

给组件的prop赋值:

<SelectTagModel
  params='params'
  visible={this.state.showTagsModel}
  onCancel={this.handleCancel.bind(this, 'tags')}
  onOk={this.handleOk.bind(this)}
  tags={tagsData['Book']}
  handleCommitTags={this.handleCommitTags.bind(this)}
  selTags={this.state.tagsArr} />

上述组件中的属性,即为调用此组件的父组件通过prop传递给SelectTagModel组件的值。

从prop中取值:

class SelectTagModal extends React.Component {
  constructor() {
    super();
  }
}

组件内部需要调用super(),才能够使用prop中的值。

在组件内部还可以使用propTypes检查组件中属性中的数据类型:

static get propTypes() {
  return {
    params: PropTypes.string.isRequired,
    visible: PropTypes.boolean.isRequired,
    onCancel: PropTypes.fn,
    onOk: PropTypes.func,
    tags: PropTypes.object.isRequired,
    handleCommitTags: PropTypes.func,
    selTags: PropTypes.array.isRequired
  };
}

二、state 

驱动组件渲染过程的除了prop,还有state,state代表组件的内部状态,记录自身的数据变化。

组件内初始化state:

class SelectTagModal extends React.Component {
  constructor() {
    super();
    this.state = {
      selectedTags: []
    };
  }
}

读取state的值:this.state.xxx;

更新state的值:this.setState({ xx: y });

三、state和props的区别:

a、prop用于定义外部接口,state用于记录内部状态;

b、prop的赋值在外部世界使用组件时调用,而state的赋值在组件内部;

c、组件不应该改变传入的prop的值,而state存在的目的就是在组件内部来改变的;

  注意:在使用过程中不应该去修改传入的props的值。

猜你喜欢

转载自blog.csdn.net/liya_nan/article/details/82758261