React基础知识(5)——React Props

state 和 props 主要的区别在于 props 是不可变的,而 state 可以根据与用户交互来改变。这就是为什么有些容器组件需要定义 state 来更新和修改数据。 而子组件只能通过 props 来传递数据。

一、使用 Props
以下实例演示了如何在组件中使用 props:

import React from 'react';
function HelloMessage(props) {
  return <h1>Hello {props.name}!</h1>;
}
export default class Home extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
        };
    }
    render() {
        return(
            <div><HelloMessage name="Runoob"/></div>
        )
    }
}

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

二、默认 Props
你可以通过组件类的 defaultProps 属性为 props 设置默认值,实例如下:
app/home/lib.js文件

import React from 'react';
export default class HelloMessage extends React.Component {
    render() {
        return (
            <h1>Hello, {this.props.name}</h1>
        );
    }
}
HelloMessage.defaultProps = {
    name: 'Runoob'
};

app/home/index.js文件

import React from 'react';
import HelloMessage from './lib';
export default class Home extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
        };
    }
    render() {
        return(
            <div><HelloMessage /></div>
        )
    }
}

三、State 和 Props
app/home/name.js

import React from 'react';
export default class Name extends React.Component {
    render() {
        return (
            <h1>{this.props.name}</h1>
        );
    }
}

app/home/link.js

import React from 'react';
export default class Link extends React.Component {
    render() {
        return (
            <a href={this.props.site}>
                {this.props.site}
            </a>
        );
    }
}

app/home/index.js

import React from 'react';
import Name from './name';
import Link from './link';
export default class Home extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            name: "菜鸟教程",
            site: "https://www.runoob.com"
        };
    }
    render() {
        return(
            <div>
                <Name name={this.state.name} />
                <Link site={this.state.site} />
            </div>
        )
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值