【问题标题】:React: Creating A Component with ES6Class and rendering it without JSXReact:使用 ES6Class 创建组件并在没有 JSX 的情况下渲染它
【发布时间】:2021-03-19 23:15:15
【问题描述】:

我刚刚开始学习 React,我正在尝试渲染我从类中创建的组件。我非常喜欢这种方式,因为它类似于我开始使用的 Java。

到目前为止,我想了解如何从头开始创建一个类并将其呈现在页面上。我在网上搜索了一下,发现了一些像 here 这样的例子,但它们不适合我的情况,因为在在这种情况下,用户正在使用我没有使用的 redux。我还发现了几个渲染示例,但它们没有明确使用类。有人可以告诉我如何成功地将代码渲染到react-container 我在这里并向我解释一下吗?非常感谢您的帮助!

class IngredientsList extends React.Component {

            renderListItem(ingredient, i) {
                return React.createElement("li", { key: i }, ingredient)
            }

            render() {
                return React.createElement("ul", { className: "ingredients" }, this.props.items.map(this.renderListItem))
            }

        }

        const myIngredients = new IngredientList();

        const items = ["1 lb Salmon", "1 cup pine nuts", "2 cups butter lettuce", "1 yellow squash", "1/2 cup Olive oil", "3 gloves of garlic"];

        const myList = myIngredients.renderListItem(items, 1);
        myIngredients.render();
<div id="react-container"></div>

如您所见,我已经创建了类,尝试初始化它,然后使用渲染方法但没有显示。我想我必须以某种方式在这里使用此方法document.getElementById('react-container') 来指向我想要渲染的位置,但我我不确定如何将它集成到我的构建中。

【问题讨论】:

    标签: javascript html reactjs


    【解决方案1】:

    在 React 中,你永远不应该在组件上调用 render 方法。 React 为您处理渲染,这也是为什么首先使用 React 的重要原因。

    您需要使用ReactDOM.render 将您的应用挂载到 DOM 中,然后 React 将从那里管理组件和子组件的渲染。

    ReactDOM.render 接受两个参数。第一个是组件,第二个是您希望应用在页面上呈现的实际 DOM 元素。

    class IngredientsList extends React.Component {
      renderListItem(ingredient, i) {
        return React.createElement("li", { key: i }, ingredient)
      }
    
      render() {
        return React.createElement("ul", { className: "ingredients" }, this.props.items.map(this.renderListItem))
      }
    }
            
    const items = ["1 lb Salmon", "1 cup pine nuts", "2 cups butter lettuce", "1 yellow squash", "1/2 cup Olive oil", "3 gloves of garlic"];
    
    ReactDOM.render(
      React.createElement(IngredientsList, {items: items}), 
      document.getElementById('react-container')
    );
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
    <div id="react-container"></div>

    【讨论】:

    • 非常感谢,效果很好。你能否也解释一下。我只需要传递类名吗?我的意思是我不需要实例化任何东西,然后反应来处理剩下的事情?我还需要在我要渲染的类组件中有一个渲染方法吗?这个方法会被react自动调用吗?
    • @helloApp 请注意,它不是类名(不是字符串),它是类的引用(不是实例类)。所以是的,React 将实例化该类,并在其上调用 render 方法。是的,您必须将方法命名为“render”,以便 React 知道调用它。
    猜你喜欢
    • 2023-02-22
    • 2016-07-13
    • 2015-01-02
    • 1970-01-01
    • 2016-09-27
    • 2020-08-18
    • 2021-03-18
    • 2021-09-22
    • 1970-01-01
    相关资源
    最近更新 更多