zoukankan      html  css  js  c++  java
  • React(六)Props属性

    state 和 props 主要的区别在于 props 是不可变的,而 state 可以根据与用户交互来改变。这就是为什么有些容器组件需要定义 state 来更新和修改数据。 而子组件只能通过 props 来传递数据。

    (1)使用Props属性

    class Mainextends React.Component {
      render() {
        return (
          <div>
            <Name name={'yulingjia'} />
          </div>
        );
      }
    }
    
    class Name extends React.Component {
      render() {
        return (
          <h1>{this.props.name}</h1>
        );
      }
    }

    (2)默认Props

    class Mainextends React.Component {
      render() {
        return (
          <h1>Hello, {this.props.name}</h1>
        );
      }
    }
    
    Main.defaultProps = {
      name: 'Yulingjia'
    };

    (3)State 和 Props

    class Main React.Component {
      constructor() {
          super();
          this.state = {
            name: "Yulingjia"
          }
        }
      render() {
        return (
          <div>
            <Name name={this.state.name} />
          </div>
        );
      }
    }
     
    class Name extends React.Component {
      render() {
        return (
          <h1>{this.props.name}</h1>
        );
      }
    }

    (3)Props 验证

    Props 验证使用 propTypes,它可以保证我们的应用组件被正确使用,React.PropTypes 提供很多验证器 (validator) 来验证传入数据是否有效。
    当向 props 传入无效数据时,JavaScript 控制台会抛出警告。

    var name= "Yulingjia";
    
    class Name extends React.Component {
      render() {
        return (
          <h1>Hello, {this.props.name}</h1>
        );
      }
    }
     
    Name.propTypes = {
      name: PropTypes.string
    };
    
    ReactDOM.render(
        <Name name={name} />,
        document.getElementById('example')
    );
  • 相关阅读:
    mongoTemplate.aggregate()聚合查询
    解决ElasticSearch5.x中@Field注解之IK分词不能用的问题
    Mybatis中使用Enum传参
    过滤,去重filter,去重reduce
    自己写的数组 方法的组合使用
    uni-app 使用vuex的方法
    uni-app实战写法
    vue的bug问题
    vuex
    vue webapp的基本功能实现方法
  • 原文地址:https://www.cnblogs.com/yulingjia/p/9722010.html
Copyright © 2011-2022 走看看