zoukankan      html  css  js  c++  java
  • 6 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')
    );

    你可以通过组件类的 defaultProps 属性为 props 设置默认值,实例如下:

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

    State 和 Props:

    如何在应用中组合使用 state 和 props,我们可以在父组件中设置 state, 并通过在子组件上使用 props 将其传递到子组件上。在 render 函数中, 我们设置 name 和 site 来获取父组件传递过来的数据。

    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.PropTypes 提供很多验证器 (validator) 来验证传入数据是否有效。当向 props 传入无效数据时,JavaScript 控制台会抛出警告。

    var title = "菜鸟教程";
    // var title = 123;
    class MyTitle extends React.Component {
      render() {
        return (
          <h1>Hello, {this.props.title}</h1>
        );
      }
    }
     
    MyTitle.propTypes = {
      title: PropTypes.string
    };
    ReactDOM.render(
        <MyTitle title={title} />,
        document.getElementById('example')
    );
  • 相关阅读:
    HDU 1800 Flying to the Mars 字典树,STL中的map ,哈希树
    字典树 HDU 1075 What Are You Talking About
    字典树 HDU 1251 统计难题
    最小生成树prim算法 POJ2031
    POJ 1287 Networking 最小生成树
    次小生成树 POJ 2728
    最短路N题Tram SPFA
    poj2236 并查集
    POJ 1611并查集
    Number Sequence
  • 原文地址:https://www.cnblogs.com/liufei1983/p/14504564.html
Copyright © 2011-2022 走看看