javascript reactjs中的渲染功能

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33465674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:31:12  来源:igfitidea点击:

Render function in reactjs

javascriptreactjs

提问by fgonzalez

Quick question. I'm learning react js.

快速提问。我正在学习 React js。

When we create a component, we provide in the render function the html template of the component to render. So far I have only seen small components with very small pieces of html, but I was just wondering what happen if we have a component with a huge html template, is there any way to provide the path to a separate html file? Or we are forced to write all the html directly inside the render function? Thanks!

当我们创建一个组件时,我们在render函数中提供了要渲染的组件的html模板。到目前为止,我只看到了带有非常小的 html 片段的小组件,但我只是想知道如果我们有一个带有巨大 html 模板的组件会发生什么,有没有办法提供单独的 html 文件的路径?或者我们被迫将所有的html直接写在render函数中?谢谢!

回答by mash

You should always write it in the render function. You're not writing HTML in there, you're writing JSX, which is compiled into Javascript. Something like <div className="test">is converted into React.createElement("div", {className: 'test'});.

你应该总是把它写在渲染函数中。你不是在那里写 HTML,而是在写 JSX,它被编译成 Javascript。类似的东西<div className="test">被转换成React.createElement("div", {className: 'test'});.

You shouldn't have an issue of size as long as you break down large components into a composition of many smaller components. You can include other components by including them in your render function, like this: <SomeComponent someProp="someVal" />.

只要您将大型组件分解为许多较小组件的组合,您就不应该有大小问题。您可以通过他们在您的渲染功能,这样包括其他组件:<SomeComponent someProp="someVal" />

回答by Anton Shuvalov

You can split your render function to the bunch of good-named methods like a partials in old plain html-templates. It's useful to make complex react-components, because you will remove big unreadable html-part from your code.

您可以将渲染函数拆分为一堆命名良好的方法,例如旧纯 html 模板中的部分。制作复杂的反应组件很有用,因为您将从代码中删除大量不可读的 html 部分。

For example, here is some pseudo-code described this approach:

例如,这里有一些伪代码描述了这种方法:

class NavBar extends React.Component {

  // Render user name and links on profile and logout 
  renderUser() {
    if (!user) return;
    return <div>{user.name}</div>;
  }

  // Render list with nav-bar items if they exists
  renderNavBarItems() {
    if (!user) return;
    return <ul>{this.items.map((i) <li><a href={i.link}>{i.name}</a></li>)}</ul>;
  }

  render() {
    return (<div className="nav-bar">
      {this.renderNavBarItems()}
      {this.renderUser()}
    </div>);
  }
}