React JSX

  • JSX:是一个 JavaScript 的语法扩展。我们建议在 React 中配合使用 JSX,JSX 可以很好地描述 UI 应该呈现出它应有交互的本质形式。

  • JSX特性:



由于 JSX 就是 JavaScript,一些标识符像 class 和 for 不建议作为 XML 属性名。
className用于代替class添加 CSS 类,就像class 在JavaScript 中的保留关键字一样。
JSX 中的属性和方法是驼峰式的——onclick将变成onClick.


案例


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <title>React 实例</title>
    <script src="https://cdn.staticfile.org/react/16.4.0/umd/react.development.js"></script>
    <script src="https://cdn.staticfile.org/react-dom/16.4.0/umd/react-dom.development.js"></script>
    <script src="https://cdn.staticfile.org/babel-standalone/6.26.0/babel.min.js"></script>
    <style>
        .title {
            font-size: 40px;
            color: chartreuse;
        }
    </style>
</head>

<body>
    <div id="app"></div>
    <script type="text/babel">
        class MyComponent extends React.Component {
            constructor(props) {
                super(props);
                this.state = {
                    isLogin: true,
                    Mystyle: {
                        fontSize: '20PX',
                        color: 'blue'
                    },
                    firstname: "我的名字是",
                    lastname: "李四",
                    list: [
                        <span>姓名:张三</span>,
                        <span>性别:男</span>,
                        <span>年龄:20</span>
                    ]
                }
            }

            render() {
                return (
                    <div>
                        {/* 运算符表达式 */}
                        <h2>{this.state.firstname + " :" + this.state.lastname}</h2>
                        <h2>{20 * 50}</h2>

                        {/* 三元运算符 */}
                         <h2>{this.state.isLogin ? "欢迎回来" : "请先登录"}</h2>

                        {/* 行内样式写法 */}
                        <p style={this.state.Mystyle}>样式写法</p>

                        {/* class样式写法 */}
                        <p className="title">class样式写法</p>


                        {/* 数组写法 正确写法 */}
                        <div>
                            { this.state.list.map((item,index) => {
                                return(
                                    <p key={index}>{index}---{item}</p>
                                )
                            })}
                        </div>

                        <p>-----分割线-------</p>
                        {/* 数组写法 上面的写法有些麻烦,可以继续简化 */}
                         <div>
                            <Info  info={this.state.list}/>
                        </div>

                    </div>
                )
            }
        }

        function Info(props){
            const list = props.info.map((item,index) => <p key={index}>{index}---{item}</p>) 
            return list
        }


        ReactDOM.render(
            <MyComponent />,
            document.getElementById('app')
        )
    </script>
</body>
</html>
powered by GitbookEdit Time: 2023-04-08 10:28:32