React学习—Props和State

1、Props
      一、定义:不管你用函数或类的方法来声明组件, 它都没法修改其自身 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" 对象。

      二、属性验证 javascript

import PropTypes from 'prop-types';

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

       -- 不一样验证器 java

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.'
      );
    }
  })
};
      三、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 };
2、state(组件的内部状态)
      一、定义初始状态: 类构造函数(class constructor) 初始化 this.state:
constructor() {
    super();
    this.state = {
        isHeartON:false
    }
}
      二、更新状态
this.setState({
    isHeartON: isHeartON
})
      三、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
      });
    });
}
相关文章
相关标签/搜索