ReactJS学习系列课程(props 组件属性)

x33g5p2x  于2022-03-06 转载在 其他  
字(2.1k)|赞(0)|评价(0)|浏览(274)

对于React而言,组件的属性在程序中,我们多用this.props获取,讲到这里,可能有些人还不清楚什么是组件的属性呢,下面我们来看段代码:

var Greet = React.createClass({
        render: function() {
          return <h1>Hello {this.props.name}</h1>;
        }
      });

      React.render(
        <Greet name="Jack" />,
        document.getElementById('container')
      );

在上面的程序中,我们首先定义了一个叫做Greet的组件,在这个组件中我们创建了一个元素,并动态赋予name属性,当我们渲染这个组件到dom上时候,定义了一个name=”Jack”的attribute,这个便是React的属性定义,如果想获取这个Jack的属性值,需要在元素中用this.props.name来获取。

对于props的定义还有另外一种写法,我们上代码:

/**
 * Created by Richard on 5/28/16.
 */
var Age = React.createClass({
    render: function(){
        return(
            <span>My Age is{this.props.age}.</span>
        )
    }
});

var Hello = React.createClass(
    {
        render:function(){
            return (
                <div>
                    <span>
                        Hello {this.props.name}.
                        <Age age={this.props.age}></Age>
                    </span>
                </div>
            )
        }
    }
);
var props = {};
props.name = "Steven";
props.age = 17;
var myHello = <Hello {...props}/>;

ReactDOM.render(
    myHello,
    document.getElementById('example')
);

我们可以声明一个props的对象,并给予两个数值,一个name,一个age, 为了简明起见,可以直接写成{…props}, 当然前面的点数可别错了哦,要不然就不工作了,大家自己动手试试吧。

同样,我们也可以对定义的属性做一定的约束,比如我们可以指定定义属性的类型(字符串,数字等等),那么怎么在React中实现呢,我们看看代码:

var MyTitle = React.createClass({
  propTypes: {
    title: React.PropTypes.string.isRequired,
  },

  render: function() {
     return <h1> {this.props.title} </h1>;
   }
});

在上面代码中,如果我们把title写成数字,将会报如下错误:

Warning: Failed propType: Invalid prop `title` of type `number` supplied to `MyTitle`, expected `string`.

对于props还有一个重要的特性,我们仍需要介绍一下,那就是,this.props.children的使用,嘿嘿,同样我们上代码:

var NotesList = React.createClass({
  render: function() {
    return (
      <ol>
      {
        React.Children.map(this.props.children, function (child) {
          return <li>{child}</li>;
        })
      }
      </ol>
    );
  }
});

ReactDOM.render(
  <NotesList>
    <span>hello</span>
    <span>world</span>
  </NotesList>,
  document.body
);

上面代码的 NoteList 组件有两个 span 子节点,它们都可以通过 this.props.children 读取,运行结果如下。

这里需要注意, this.props.children 的值有三种可能:如果当前组件没有子节点,它就是 undefined ;如果有一个子节点,数据类型是 object ;如果有多个子节点,数据类型就是 array 。所以,处理 this.props.children 的时候要小心。

React 提供一个工具方法 React.Children 来处理 this.props.children 。我们可以用 React.Children.map 来遍历子节点,而不用担心 this.props.children 的数据类型是 undefined 还是 object。更多的 React.Children 的方法。

好了,props属性问题,我们就介绍这么多了,希望大家在使用过程中不断摸索吧。

谢谢!

相关文章