React系列教程:6. 子组件

函数组件

// src/components/Hello1.jsx

import { useState } from 'react'

function Hello1 (props) {
    const [ hello1, setHello1 ] = useState('world1')
    setTimeout(() => {
        setHello1('world2')
    }, 2000)
    return (
        <div>
            {/* <Hello1>hello1</Hello1>中间的内容就是children */}
            {props.children}
        </div>
    )
}

export default Hello1;

类组件

// src/components/Hello2.jsx

import React from "react";

class Hello2 extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            hello2: 'world2'
        }
    }

    render() {
        setTimeout(() => {
            this.setState({
                hello2: 'world22'
            })
        }, 2000)
        return (
            <div>
                {/* <Hello1>hello1</Hello1>中间的内容就是children */}
                {this.props.children}
            </div>
        )
    }

}

export default Hello2
posted @ 2025-11-05 11:18  龚思凯1  阅读(3)  评论(0)    收藏  举报