React学习—Props和State

一、Props
      1、定义:无论你用函数或类的方法来声明组件, 它都无法修改其自身 props. 在React中代表着数据,组件之间的数据传递是通过props进行的。
function Welcome(props) {
     return <h1>Hello, {props.name}</h1>;
}
const element = <Welcome name="Sara" />;
ReactDOM.render(
     element,
     document.getElementById('root')
);
// 当 React 遇到一个代表用户定义组件的元素时,它将 JSX 属性以一个单独对象的形式传递给相应的组件。 我们将其称为 "props" 对象。

      2、属性验证 

import PropTypes from 'prop-types';

class Greeting extends React.Component {
  render() {
    return (
      <h1>Hello, {this.props.name}</h1>
    );
  }
}
Greeting.propTypes = {
  name: PropTypes.string
}

       -- 不同验证器 

import PropTypes from 'prop-types';
MyComponent.propTypes = {
  // 你可以声明一个 prop 是一个特定的 JS 原始类型。
  // 默认情况下,这些都是可选的。
  optionalArray: PropTypes.array,
  optionalBool: PropTypes.bool,
  optionalFunc: PropTypes.func,
  optionalNumber: PropTypes.number,
  optionalObject: PropTypes.object,
  optionalString: PropTypes.string,
  optionalSymbol: PropTypes.symbol,
  // 任何东西都可以被渲染:numbers, strings, elements,或者是包含这些类型的数组(或者是片段)。
  optionalNode: PropTypes.node,
  // 一个 React 元素。
  optionalElement: PropTypes.element,
  // 你也可以声明一个 prop 是类的一个实例。
  // 使用 JS 的 instanceof 运算符。
  optionalMessage: PropTypes.instanceOf(Message),
  // 你可以声明 prop 是特定的值,类似于枚举
  optionalEnum: PropTypes.oneOf(['News', 'Photos']),
  // 一个对象可以是多种类型其中之一
  optionalUnion: PropTypes.oneOfType([
    PropTypes.string,
    PropTypes.number,
    PropTypes.instanceOf(Message)
  ]),
  // 一个某种类型的数组
  optionalArrayOf: PropTypes.arrayOf(PropTypes.number),
  // 属性值为某种类型的对象
  optionalObjectOf: PropTypes.objectOf(PropTypes.number),
  // 一个特定形式的对象
  optionalObjectWithShape: PropTypes.shape({
    color: PropTypes.string,
    fontSize: PropTypes.number
  }),
  // 你可以使用 `isRequired' 链接上述任何一个,以确保在没有提供 prop 的情况下显示警告。
  requiredFunc: PropTypes.func.isRequired,
  // 任何数据类型的值
  requiredAny: PropTypes.any.isRequired,
  // 你也可以声明自定义的验证器。如果验证失败返回 Error 对象。不要使用 `console.warn` 或者 throw ,
  // 因为这不会在 `oneOfType` 类型的验证器中起作用。
  customProp: function(props, propName, componentName) {
    if (!/matchme/.test(props[propName])) {
      return new Error(
        'Invalid prop `' + propName + '` supplied to' +
        ' `' + componentName + '`. Validation failed.'
      );
    }
  },
  // 也可以声明`arrayOf`和`objectOf`类型的验证器,如果验证失败需要返回Error对象。
  // 会在数组或者对象的每一个元素上调用验证器。验证器的前两个参数分别是数组或者对象本身,
  // 以及当前元素的键值。
  customArrayProp: PropTypes.arrayOf(function(propValue, key, componentName, location, propFullName) {
    if (!/matchme/.test(propValue[key])) {
      return new Error(
        'Invalid prop `' + propFullName + '` supplied to' +
        ' `' + componentName + '`. Validation failed.'
      );
    }
  })
};
      3、context 跨层级数据传递
const PropTypes = require('prop-types');
class Button extends React.Component {
   render() {
      return (
         <button style={{background: this.context.color}}>
             {this.props.children}
        </button>
      );
  }
}
Button.contextTypes = {
  color: PropTypes.string
};
class Message extends React.Component { render() { return ( <div> {this.props.text} <Button>Delete</Button> </div> ); } }
class MessageList extends React.Component { getChildContext() { return {color: "purple"}; } render() { const children = this.props.messages.map((message) => <Message text={message.text} /> ); return <div>{children}</div>; } }
MessageList.childContextTypes
= { color: PropTypes.string };
二、state(组件的内部状态)
      1、定义初始状态: 类构造函数(class constructor) 初始化 this.state:
constructor() {
    super();
    this.state = {
        isHeartON:false
    }
}
      2、更新状态
this.setState({
    isHeartON: isHeartON
})
      3、state(状态)更新会被合并
      合并是浅合并,所以 this.setState({comments}) 不会改变 this.state.posts 的值,但会完全替换this.state.comments 的值。
constructor(props) {
    super(props);
    this.state = {
      posts: [],
      comments: []
    };
}
componentDidMount() {
    fetchPosts().then(response => {
      this.setState({
        posts: response.posts
      });
    });
    fetchComments().then(response => {
      this.setState({
        comments: response.comments
      });
    });
}

  

转载于:https://www.cnblogs.com/nankeyimeng/p/7233993.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值