reactjs中的render和return有什么区别? [英] What is the difference between render and return in reactjs?

查看:71
本文介绍了reactjs中的render和return有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 JavaScript 的新手.我看到很多地方使用 returnrender 只是想知道它们之间有什么区别.

I am new to JavaScript. I see lot of places return and render being used just want to know what's the difference between them.

推荐答案

render 在编写 React 组件时需要使用类方法

render method is required when you are writing a React component using as a class method

根据文档:

render() 方法是必需的.

当被调用时,它应该检查 this.propsthis.state 和返回以下类型之一:

When called, it should examine this.props and this.state and return one of the following types:

React 元素. 通常通过 JSX 创建.元素可以是原生 DOM 组件 (<div/>) 的表示,也可以是一个用户定义的复合组件().

React elements. Typically created via JSX. An element can either be a representation of a native DOM component (<div />), or a user-defined composite component (<MyComponent />).

字符串和数字.这些在 DOM 中呈现为文本节点.

String and numbers. These are rendered as text nodes in the DOM.

门户. 使用 ReactDOM.createPortal 创建.空值.什么都不渲染.

Portals. Created with ReactDOM.createPortal. null. Renders nothing.

布尔值. 不渲染任何内容.(主要存在以支持返回测试 && 模式,其中 test 是布尔值.)

Booleans. Render nothing. (Mostly exists to support return test && pattern, where test is boolean.)

本质上,render 是一种生命周期方法,每当组件需要更新时都会调用它.

Essentially render is kind of a lifecycle method which is invoked whenever the component needs to update.

至于 return 语句,它用于返回 data/response/JSX 元素,具体取决于它的使用位置.如果在渲染方法中使用,您需要返回上述指定类型之一(反应元素、字符串和数字、门户或布尔值).

As for the return statement, its used to return the data/response/JSX elements depending on where it is used. If used in render method you need to return one of the above specified types(React elements, Strings and numbers, Portals or Booleans).

return 从其他函数可以返回从函数计算的值或 returnrender 方法中要渲染的 React 元素

return from other function can either return the value evaluated from the function or return the React elements to be rendered in the render method

Functional components 不定义 render 方法,而是使用 explicit return statement 返回 React 元素隐式返回

Functional components don't define a render method, instead they return the React elements using an explicit return statement or an implicit return

例如:显式返回

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

例如:隐式返回

const Welcome = (props) => (
     <h1>Hello, {props.name}</h1>;
)

这篇关于reactjs中的render和return有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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