React.js 官网资料摘记:组件&Props

组件&Props

跟着官网上的尝试过五子棋例子的,应该能看懂官网上的这么一段介绍:

组件可以将UI切分成一些的独立的、可复用的部件,这样你就只需专注于构建每一个单独的部件。
组件从概念上看就像是函数,它可以接收任意的输入值(称之为“props”),并返回一个需要在页面上展示的React元素。

的确,React开发时,你可以设计一个一个小型的组件,再把这些组件组合起来,就能构建复杂的页面了。

函数定义/定义组件类

定义一个函数就像定义一个javascript函数一样:

function Welcome(parameter){
    return <h1>{parameter.title}</h1>
}

定义一个组件有点像面向对象编程中的编写一个类的继承一样,其实是很像:

class World extends React.Component{
    render(){
        return <h1>{this.props.title}</h1>
    }
}

classReact中被当作关键字来使用了,这里是不是很像定义了一个类World,该类继承了React.Component类,并重写了其中的render()方法。

组件渲染

上面我们遇到的React元素都是DOM标签,其实组件调用,组件调用,是这么调用的:

class Example extends React.Component{
    render(){
        return (
            <h1>{this.props.title}</h1>
        );
    }
}
ReactDOM.render(
    <Example title='组件调用演示'/>,
    document.getElementById("root")
);

组件名称必须以大写字母开头!!!

组合组件

组件与组件之间也是可以直接调用的,例如上面我们创建了组件Welcome,下面我们就在一个新的组件App中调用该组件:

class App extends React.Component{
    render(){
        return(
            <div>
                <Welcome title='第一个组件' />
                <Welcome title='第二个组件' />
            </div>
        );
    }
}
ReactDOM.render(
    <App />,
    document.getElementById("root")
);

警告:
组件的返回值只能有一个根元素。这也是我们要用一个<div来包裹所有<Welcome />元素的原因。

组件提取

拿官网上的例子来说,假设我们要返回的一个渲染结果很复杂,如下面所示:

function Common(props){
    return (
        <div className="Comment">
          <div className="UserInfo">
         <img className="Avatar"
          src={props.author.avatarUrl}
          alt={props.author.name}
         />
         <div className="UserInfo-name">
           {props.author.name}
         </div>
       </div>
       <div className="Comment-text">
         {props.text}
       </div>
       <div className="Comment-date">
         {formatDate(props.date)}
       </div>
     </div>
    );
}

不用深究其中的内容了,只要知道如何把上面那团乱麻解开就行了:

function Avatar(props){
    return (
     <img className="Avatar"
      src={props.user.avatarUrl}
      alt={props.user.name}
    />
    );
}
function UserInfo(props){
    return(
        <div className="UserInfo">
          <Avatar user={props.user} />
          <div className="UserInfo-name">
            {props.user.name}
          </div>
        </div>
    );
}
function Common(props){
    return (
        <div>
            <UserInfo user={props.author}/>
            <div className='Commom-text'>
                {props.text}
            </div>
            <div className='Common-date'>
                <!--这里的formateDate是javascript的原生函数-->
                {formateDate(props.date)}
            </div>
        </div>
    );
}

Props的只读性

我们上面使用过this.props.Parameter来读取过用户的输入,但是记住!只能读取用户的输入,不能修改this.props.Parameter的值,就是不能给他赋值,这是React的严格规则

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值