React渲染和事件处理

时间:2022-12-20 08:51:48

一、列表渲染

①在列表中,绑定数组成员会直接把成员渲染

    <div id="app"></div>
    <script src="node_modules/@babel/standalone/babel.js"></script>
    <script src="node_modules/react/umd/react.development.js"></script>
    <script src="node_modules/react-dom/umd/react-dom.development.js"></script>
    <script type="text/babel">
        const fruits =[
            <li key='one'>apple</li>,
            <li key='two'>orange</li>,
            <li key='three'>banana</li>,
        ]
        const element = (
            <div>
                <ul>{fruits}</ul>
            </div>
        )
        ReactDOM.render(element,document.getElementById('app'))
    </script>

React渲染和事件处理

②当数组成员是对象时,可以直接在标签中生成一个数组

    <div id="app"></div>
    <script src="node_modules/@babel/standalone/babel.js"></script>
    <script src="node_modules/react/umd/react.development.js"></script>
    <script src="node_modules/react-dom/umd/react-dom.development.js"></script>
    <script type="text/babel">
        const todos = [
            {id:1,name:'eric'},
            {id:2,name:'marry'},
            {id:3,name:'jack'},
            {id:4,name:'lisa'},
        ]
        
        const element = (
            <div>
                <ul>
                    {
                        todos.map(item => {
                            return <li key={item.id}>{item.name}</li>
                        })
                    }
                </ul>
            </div>
        )
        ReactDOM.render(element,document.getElementById('app'))
    </script>

React渲染和事件处理

二、条件渲染

    <div id="app"></div>
    <script src="node_modules/@babel/standalone/babel.js"></script>
    <script src="node_modules/react/umd/react.development.js"></script>
    <script src="node_modules/react-dom/umd/react-dom.development.js"></script>
    <script type="text/babel">
        const user ={
            name:'eric',
        }
        function getHi(user) {
            if (user) {
                return <h1>hello {user.name}</h1>
            }
            return <h1>hello world</h1>
        }
        const element = getHi(user)
        //const element = getHi()
        ReactDOM.render(element,document.getElementById('app'))
    </script>

React渲染和事件处理

三、事件处理

    <div id="app"></div>
    <script src="node_modules/@babel/standalone/babel.js"></script>
    <script src="node_modules/react/umd/react.development.js"></script>
    <script src="node_modules/react-dom/umd/react-dom.development.js"></script>
    <script type="text/babel">
        function handleClick() {
            window.alert('hello')
        }
        // 事件使用驼峰命名
        // 必须绑定一个函数,行数体不能写在行内,也可以直接绑定一个匿名函数
        // 不能使用字符串的方式,一定要用{函数}来绑定
        const element = (
            <div>
                <button onClick={handleClick}>点击1</button>
                <button onClick={()=>{alert('world')}}>点击2</button>
            </div>
        )

        ReactDOM.render(element,document.getElementById('app'))
    </script>

React渲染和事件处理