zoukankan      html  css  js  c++  java
  • React文档(二十)不使用JSX

    JSX并不是使用React的一个强制需求。当你不需要在你的构造环境里设置编译那么不使用JSX会很方便。

    每一个JSX元素只是调用React.createElement(componnet, props, ...children)的语法糖。因此,JSX能做的事原生js同样也做得到。

    举个例子,下面的代码用JSX:

    class Hello extends React.Component {
      render() {
        return <div>Hello {this.props.toWhat}</div>;
      }
    }
    
    ReactDOM.render(
      <Hello toWhat="World" />,
      document.getElementById('root')
    );
    如果不使用JSX可以被编译成这样的代码:
    class Hello extends React.Component {
      render() {
        return React.createElement('div', null, `Hello ${this.props.toWhat}`);
      }
    }
    
    ReactDOM.render(
      React.createElement(Hello, {toWhat: 'World'}, null),
      document.getElementById('root')
    );

    如果你好奇想看更多的例子JSX被转变成js,你可以试一试在线Babel编译器

    组件要么被提供为一个字符串,要么是一个React.Component子类,要么是一个无状态组件的函数。

    如果你已经厌倦了React.createElement方法,一个普通模式是使用简写:

    const e = React.createElement;
    
    ReactDOM.render(
      e('div', null, 'Hello World'),
      document.getElementById('root')
    );

    如果你对React.createElement使用这种简写,那么不使用JSX语法也一样方便。

    其它选择的话,你可以去参考社区上的项目例如react-hyperscript和 hyperscript-helpers 。它们都提供了一些简洁的语法。
  • 相关阅读:
    mysql-数据库增删改查
    判断,循环
    数组
    html 三种垂直居中
    箭头函数
    Array类型
    object
    JAVA WEB 行业技术
    一个好的程序员
    经典语录
  • 原文地址:https://www.cnblogs.com/hahazexia/p/6484427.html
Copyright © 2011-2022 走看看