Getting started with react - creating components (2) stateless function method

It's about inheritance React.Component Create the react component.
The React component can also be constructed by stateless function.

give an example

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>React Components</title>
</head>
<body>

<!-- Target Container -->
<div id="react-container"></div>

<!-- React Library & React DOM-->
<script src="https://unpkg.com/react@16/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16/umd/react-dom.development.js"></script>

<script>
    const foodList = ({items}) =>
        React.createElement(
              "ul", 
              {className: "food-list"},
             items.map((item, i) =>
                React.createElement("li", { key: i }, item)
             )
     )

    const items = [
        "1 apple",
        "1 banana",
        "2 oranges",
        "2 tomatos"
    ]
    ReactDOM.render(
      React.createElement(foodList, {items}, null),
      document.getElementById('react-container')
    )
</script>

</body>
</html>

Declare a stateless function foodList: where
items is the parameter passed in;
React.createElement Is the function body and return value

const foodList = ({items}) =>
        React.createElement(
              "ul", 
              {className: "food-list"},
             items.map((item, i) =>
                React.createElement("li", { key: i }, item)
        )
 )

Another anonymous function is items.map () functions passed in as parameters
item is each value in the items array. I is the index of the items array. item = items [i]

items.map((item, i) =>
       React.createElement("li", { key: i }, item)
)

The purpose of this sentence is to convert each value in items into a React Element.
Each item is constructed as < li > of the corresponding html, which contains the attribute of a key and the content of the item.

ReactDOM.render(
      React.createElement(foodList, {items}, null),
      document.getElementById('react-container')
)

When rendering with react DOM, construct the stateless function foodList created earlier React.createElement , and pass in the argument {items}.

Tags: React Attribute

Posted on Sat, 30 May 2020 08:30:02 -0700 by bhogg