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 。它们都提供了一些简洁的语法。
  • 相关阅读:
    [jdk] JDK1.5新特性
    [maven] maven介绍
    [Ant] bulid.xml配置详解
    [spring] spring面试题
    .net(C#)时间相减、C#计算时间间隔
    如何记录应用程序日志
    交换机、集线器、路由器区别和使用浅谈
    ASP.NET 在域控制器上使用默认 ASPNET 帐户不能正常运行
    .NET 4中Entity Framework简介
    WCF传输性能测试
  • 原文地址:https://www.cnblogs.com/hahazexia/p/6484427.html
Copyright © 2011-2022 走看看