本章主要介绍React的工作原理,首先理解以下几个概念:
定义了所有 HTML 元素的对象和属性,以及访问它们的方法;HTML DOM 是关于如何获取、修改、添加或删除 HTML 元素的标准。
例如
一个DOM元素。
JavaScript可以用来与浏览器进行交互以修改DOM对象的集合。
document.createElement
document.appendChild
是一个JS库,用来帮助我们操作DOM,不用我们直接访问DOM API。
React element:声明一个DOM元素并进行样式的描述。
是个简单用Reat创建一个DOM例子:
React Samples
其中log的输出是一个React element 的结构:
{
$$typeof: Symbol(React.element),
"type": "h1",
"key": null,
"ref": null,
"props": {id: "recipe-0", children: "Baked Salmon"},
"_owner": null,
"_store": {}
}
React element Children:React 获取他的子元素使用props.children:
const list = React.createElement(
"ul",
null,
React.createElement("li", null, "2 lb salmon"),
React.createElement("li", null, "5 sprigs fresh rosemary"),
React.createElement("li", null, "2 tablespoons olive oil"),
React.createElement("li", null, "2 small lemons"),
React.createElement("li", null, "1 teaspoon kosher salt"),
React.createElement("li", null, "4 cloves of chopped garlic")
);
console.log(list);
其中log的输出是一个React element Children的结构:
{
"type": "ul",
"props": {
"children": [
{ "type": "li", "props": { "children": "2 lb salmon" } … },
{ "type": "li", "props": { "children": "5 sprigs fresh rosemary"} … },
{ "type": "li", "props": { "children": "2 tablespoons olive oil" } … },
{ "type": "li", "props": { "children": "2 small lemons"} … },
{ "type": "li", "props": { "children": "1 teaspoon kosher salt"} … },
{ "type": "li", "props": { "children": "4 cloves of chopped garlic"} … }
]
...
}
}
React Components: 组件允许我们重用相同的结构,然后可以用不同的数据集复用这些结构。
const secretIngredients = [
"1 cup unsalted butter",
"1 cup crunchy peanut butter",
"1 cup brown sugar",
"1 cup white sugar",
"2 eggs",
"2.5 cups all purpose flour",
"1 teaspoon baking powder",
"0.5 teaspoon salt"
];
// 使用函数实现组件
// function IngredientsList(props) {
// return React.createElement(
// "ul",
// { className: "ingredients" },
// props.items.map((ingredient, i) =>
// React.createElement("li", { key: i }, ingredient)
// )
// );
// }
// 使用类的方式实现组件
class IngredientsList extends React.Component {
render() {
return React.createElement(
"ul",
{ className: "ingredients" },
this.props.items.map((ingredient, i) =>
React.createElement("li", { key: i }, ingredient)
)
);
}
}
ReactDOM.render(
React.createElement(IngredientsList, { items: secretIngredients }, null),
document.getElementById("root")
);