参考:
官方tutorial
我一直没看懂里面这个this
菜鸟教程
What is React
- React 是一个用于构建用户界面的 JAVASCRIPT 库。
- React主要用于构建UI,很多人认为 React 是 MVC 中的 V(视图)。
- React is a JavaScript library
- React is a User Interface (UI) library
- React is a tool for building UI components
Basic React Logic
JSX
Most React developers use a special syntax called “JSX” which makes these structures easier to write. The <div /> syntax is transformed at build time to React.createElement(‘div’). put any JavaScript expressions within braces inside JSX. Each React element is a JavaScript object that you can store in a variable or pass around in your program.
- JSX stands for JavaScript XML.
JSX is an XML/HTML like extension to JavaScript.(是一种可以用HTML tag的JavaScript) - not JavaScripte not HTML
- JSX is a XML syntax extension to JavaScript
- Just like HTML, JSX tags can have a tag names, attributes, and children.
What is the HTML DOM?
- The HTML DOM is an Object Model for HTML.
- The HTML DOM is an API (Programming Interface) for JavaScript
So: JavaScript can edit HTML(elements, attributes,CSS, events)
use babel
<script type="text/babel">
// JSX Babel code goes here
</script>
How react interact with HTML
- we inheritance our components from React.Component
- pass value by props
this.props.value
- remember value by state
this.state.value
,this.setState({value:'x'})
component(组件)
- 使用function or class 来定义一个component
// by function
function HelloMessage(props) {
return <h1>Hello World!</h1>;
}
// by class
class Welcome extends React.Component {
render() {
return <h1>Hello World!</h1>;
}
}
Props
state 和 props 主要的区别在于 props 是不可变的,而 state 可以根据与用户交互来改变。这就是为什么有些容器组件需要定义 state 来更新和修改数据。 而子组件只能通过 props 来传递数据。
- Passing data through Props(passing between different component)
- Passing props is how information flows in React apps, from parents to children.
- in constructor: always inheritance the superclass’s constructor by using
super(props)
ReactDom.render()
is used to render (display) HTML elements(添加innerHTML):
- react element:
const element = <h1>Hello React!</h1>
- react component:
function Welcome() { return <h1>Hello React!</h1>;}
然后可以运行render()函数
ReactDOM.render(element/ component, document.getElementById('root'));
State
To remembers things, components use state
- React 里,只需更新组件的 state,然后根据新的 state 重新渲染用户界面(不要操作 DOM)。
- render() 方法中使用 this.state
- 类组件应始终使用 props 调用基础构造函数。
class Clock extends React.Component {
constructor(props) {
// 必须有super(props)这个继承
super(props);
// 初始化this.state
this.state = {date: new Date()};
}
render() {
return (
<div>
<h1>Hello, world!</h1>
<h2>现在是 {this.state.date.toLocaleTimeString()}.</h2>
</div>
);
}
}
ReactDOM.render(
<Clock />,
document.getElementById('example')
);
How to begin
what is Webpack, Babel, ESLint在这里插入代码片