React 中大括号的使用 [英] Use of curly braces in React

查看:34
本文介绍了React 中大括号的使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试学习 React.我在使用花括号时遇到问题.花括号的使用使 JSX 和 JS 有所不同在下面的代码中,Curly Brace 1 说现在是 JS".为什么有花括号 2 ?它已经在花括号区域内?

I am trying to learn React. I am having trouble with the use of curly braces. Use of curly brace makes difference between JSX and JS In the code below, Curly Brace 1 says "now it is JS". Why is there curly brace 2 ? It is already inside a curly brace zone ?

var React = require('react');
var ReactDOM = require('react-dom');

var MyCompClass = React.createClass({ // open curly brace 1
  render: function () { // open curly brace 2
    return <h1>Hello</h1>;
  }
});

ReactDOM.render(
    <MyCompClass />, 
    document.getElementById('app')
);

第二个问题:

ReactDOM.render(
        <MyCompClass />, 
        document.getElementById('app')
    ); 

为什么 .render() 在 MyComponentClass 周围需要 HTML 标记?

why do .render() need HTML marks around MyComponentClass ?

感谢您的帮助!

推荐答案

您正在使用对象参数调用 React.createClass 方法.第一个花括号是标准 javascript 对象的语法.在这个对象中有一个叫做render"的属性.这个渲染属性可以是一个函数,所以第二个花括号是javascript函数语法的范围.

You are calling React.createClass method with object parameter. The first curly braces is the syntax of standard javascript object. In this object there is a property called as 'render'. This render attribute could be a function, so the second curly braces are the scope of javascript function syntax.

此外,render 方法中的 HTML 标记是您的 React 组件,这是 JSX 语法.

Also, the HTML marks in your render method is your React component and this is JSX syntax.

因此,以下文档可能会有所帮助:

So, the following documentations may be helpful:

  1. 不使用 ES6 做出反应
  2. 介绍 JSX
  3. 不使用 JSX 进行响应

另外,我意识到 React props 的使用可能会让你感到困惑.在反应中,道具的语法再次使用花括号,但这用于为您的组件提供动态绑定.通过使用此语法,如果 prop 的值发生更改,您的组件将能够更新您的 html.下面是这个案例的例子:

Also, I realized that React props usage may cause confusion for you. In react, the syntax of props usage again with curly braces but this is used to provide dynamic binding for your components. By using this syntax, your component will be able to update your html, if the value of your prop is changed. The following is the example of this case:

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

const element = <Welcome name="Sara" />;
ReactDOM.render(
  element,
  document.getElementById('root')
);

更多详细信息,请查看组件的相关React文档和道具使用.

For more detailed information, please examine the related React document for Component and Props usage.

这篇关于React 中大括号的使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆