反应组件没有功能或 Class?

React Component without Function or Class?

有时,我看到并写过一些像这样的 React 代码。

const text = (
  <p>
    Some text
  </p>
);

这确实有效,但是有什么问题吗?

我知道我不能以这种方式使用道具,但如果我所做的只是渲染一些简单的东西,比如一段话,我不明白为什么我需要将它变成一个功能组件或扩展 React.Component

我目前这样做的原因是因为我需要传递一两段作为占位符文本,而我不能只传递纯文本。

这不是一个react组件,它只是一个存储了JSX的变量:

const text = (
   <p>
      Some text
   </p>
);

根据DOC

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

This funny tag syntax is neither a string nor HTML.

It is called JSX, and it is a syntax extension to JavaScript. We recommend using it with React to describe what the UI should look like. JSX may remind you of a template language, but it comes with the full power of JavaScript.

props 将仅在 React 组件 中可用,无论是在功能组件还是基于 Class 的组件中。

Why React is required in this if it is not a react component?

我们可以将 JSX 存储在任何变量中,它会被 babel 转译并转换为 React.createElement.

根据DOC

JSX just provides syntactic sugar for the React.createElement() function.

Since JSX compiles into calls to React.createElement, the React library must also always be in scope from your JSX code.

例子:当我们写:

var a = <div> Hello </div>

Result 其中:

var a = React.createElement(
  "div",
  null,
  " Hello "
);

此代码只是将段落元素及其中的文本存储到变量 text 中。它不是一个组件,功能或其他。像标准 Javascript:

一样在 React 组件中使用它
render() {
    return (
        <div className="some-text">
            { text }
        </div>
    );
}