React Props

一、React Props

state和props的主要区别在于props是不可变的,而state可以根据与用户交互来改变;

这就是为什么有些容器组件需要定义state来更新和修改数据,而子组件只能通过props来修改数据。

二、使用Props

function HelloMessage(props) {
    return <h1>Hello {props.name}</h1>;
}
const element = <HelloMessage name="Runoob" />;
ReactDOM.render(
    element,
    document.getElementById('example')
);

实例中name属性通过props.name来获取。

三、默认Props

可以通过组件类的defaultProps属性为props设置默认值

class HelloMessage extends React.Component {
    render() {
        return (
            <h1>Hello, {this.props.name}</h1>
        )
    }
}
HelloMessage.defaultProps = {
    name:'Runoob'
};
const element = <HelloMessage/>;
ReactDOMrender(
    element,
    document.getElementById('example')
);

四、State和Props

class WebSite extends React.Component {
  constructor() {
      super();
 
      this.state = {
        name: "菜鸟教程",
        site: "https://www.runoob.com"
      }
    }
  render() {
    return (
      <div>
        <Name name={this.state.name} />
        <Link site={this.state.site} />
      </div>
    );
  }
}
 
 
 
class Name extends React.Component {
  render() {
    return (
      <h1>{this.props.name}</h1>
    );
  }
}
 
class Link extends React.Component {
  render() {
    return (
      <a href={this.props.site}>
        {this.props.site}
      </a>
    );
  }
}
 
ReactDOM.render(
  <WebSite />,
  document.getElementById('example')
);

五、Props验证

Props 验证使用了propTypes,它可以保证我们的应用组件被正确使用,React.PropType提供了很多验证器(validator)来验证传入的数据是否有效。

当向props传入无效数据时,JavaScript控制台会抛出警告。

以下实例创建一个Mytitle组件,属性title是必须的且是字符串,非字符串类型会自动转换成字符串;

var title = "菜鸟教程";
// var title = 123;
var MyTitle = React.createClass({
  propTypes: {
    title: React.PropTypes.string.isRequired,
  },
 
  render: function() {
     return <h1> {this.props.title} </h1>;
   }
});
ReactDOM.render(
    <MyTitle title={title} />,
    document.getElementById('example')
);

 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值