Contents:
- What is react?
- React element
- React component
- render()
- React is a Javascript library
- High performance frontend framework
- Use small and isolated pieces of UI code called “components”
Initialize React App
npx create-react-app my-app
cd my-app
npm start
App structure
-
manifest.json 指定了开始页面
-
index.html,一切都从这里开始,这个是代码执行的源头。
-
src/index.js 是一个入口文件
React.Component
class ShoppingList extends React.Component {
render(){
return(
//...
)
}
}
React element
- React UI的最小单元
- 不可变:当元素被创建之后,你是无法改变其内容或属性的
- 可以被render进react DOM,并由其来管理
render()
- A method that returns a description of what you want to see on the screen
- The description is called a react element
- React display the view using the react elements returned
将React元素render到DOM root
const element = <h1>Hello, world!</h1>;
ReactDOM.render(
element,
document.getElementById('example')
);
function封装react element
// function that return JSX.element
function Clock(props) {
return (
<div>
<h1>Hello, world!</h1>
<h2>现在是 {props.date.toLocaleTimeString()}.</h2>
</div>
);
}
// function that renders element
function tick() {
ReactDOM.render(
<Clock date={new Date()} />,
document.getElementById('example')
);
}
// repeatedly calling the rendering function -- 每秒钟调用一次
setInterval(tick, 1000);
Component封装element
React.component
class Clock extends React.Component {
render(){
return(
...
<h2>现在是 {this.props.date.toLocaleTimeString()}.</h2>
...
)
}
}
function tick() {
...
}
setInterval(tick, 1000);
- ShoppingList: React component class
-
Responsibility:
- A component takes in parameters, called
props
- Returns a hierarchy of views
- Display via the
render
method
- A component takes in parameters, called