码迷,mamicode.com
首页 > 其他好文 > 详细

React(六)Props属性

时间:2018-09-29 10:18:29      阅读:144      评论:0      收藏:0      [点我收藏+]

标签:ntb   为什么   rop   应用   this   component   div   更新   控制   

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‘)
);

 

React(六)Props属性

标签:ntb   为什么   rop   应用   this   component   div   更新   控制   

原文地址:https://www.cnblogs.com/yulingjia/p/9722010.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!