react-jsx

作者: _undefined | 来源:发表于2020-08-20 14:46 被阅读0次

    jsx 是类似 js 模板语法

    声明 jsx

    const element = <h1>Hello, world!</h1>;
    

    使用 jsx

    ReactDOM.render(
        element,
        document.getElementById('app')
    );
    

    jsx 语法

    • jsx 是 js 的语法扩展,在 jsx 中可以使用所有 js 表达式,变量都用 { 表达式 } 花括号格式。
    • 样式名 class 变为 className
    • 内联样式 style 变为对象,对象的键名使用小驼峰格式,如:style={{fontSize: '16px'}}
    • 事件由原生事件变为小驼峰格式,如:onClick
    • jsx 内部注释使用 {/* 注释 */}
    • 条件判断使用 &&|| 或者三元运算符。

    jsx 插入变量

    let msg = 'world'
    const element = <h1>Hello, {msg}!</h1>;
    

    jsx 样式名 class 变为 className

    const element = <h1 className="heading">Hello, world!</h1>;
    

    jsx 内联样式 style 变为对象,对象的键名使用小驼峰格式

    let myStyle = {
        fontSize: '16px'
    }
    const element = <h1 className="heading" style={myStyle}>Hello, world!</h1>;
    

    jsx 事件名 onclick 变为 onClick

    const element = <h1 className="heading" onClick={this.eventName.bind(this)}>Hello, world!</h1>;
    // 或者
    const element = <h1 className="heading" onClick={event => this.eventName()}>Hello, world!</h1>;
    

    jsx 条件判断

    // &&
    let flag = true;
    const element = {flag && <h1>Hello, world!</h1>};
    // ||
    const element = {flag && <h1>Hello, world!</h1> || '<h1>你好, 世界!</h1>'};
    // 三元运算符
    const element = {flag ? <h1>Hello, world!</h1> : '<h1>你好, 世界!</h1>'};
    

    jsx 列表循环 map

    const list = ['苹果', '香蕉', '橘子'];
    const element = (
        <ul>
            {
                list.push('火龙果'),
                
                list.map(item => {
                    return <li key={item}>{item}</li>
                })
            }
        </ul>
    );
    

    jsx 组件

    普通的 js 函数(无状态组件)

    function Hello() {
        return <h1>Hello, world!</h1>;
    }
    
    

    ES6 class

    class Hello extends React.Component {
        render() {
            return <h1>Hello, world!</h1>;
        }
    }
    

    相关文章

      网友评论

          本文标题:react-jsx

          本文链接:https://www.haomeiwen.com/subject/jbgsjktx.html