react是facebook推出的一个mvc的 JavaScript 库,与传统的页面相比,拥有以下特点:
组件化:将页面元素组件化,代码可重用性高
声明式:采用声明范式,轻松描述页面
灵活:能够和已知库或框架很好地配合
高效:使用模拟DOM的思想,大大减少与DOM的交互
面向对象化:封装组件内部的各类资源和数据流动,将其看成一个整体处理,而不是一个部分React就是将已有的页面元素的资源(html,css,js,json,img)等整合到一起并且封装成可重用的组件的一个JavaScript框架。
使用react创建一个单页说明下(以下环境为webpack4)
//app.js
import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render( <h4>Hello World!</h4>, document.getElementById('app') );这样就能看到 Hello World!
对以上代码进行组件改造和数据单向传递
import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component{
constructor(props){
super(props);
}
render(){
return (
<h4> {this.props.data} </h4>
);
}
}
ReactDOM.render( <App data='Hello World!'>, document.getElementById('app') );再进行react列表渲染及组件式布局
import React, { Fragment } from 'react',
import ReactDOM from 'react-dom';
class Head extends React.Component{
constructor(props){
super(props);
}
render(){
return (
<h4>{ this.props.head }</h4>
)
}
}
class App extends React.Component{ constructor(props){
super(props);
this.state = {
list:['今天干什么','吃饭','喝水','休息','工作','上班']
}
}
render(){
const listItem = this.state.list.map((item, index) =>
return <li key={index}>{item}</li>
);
return (
<Fragment>
<Head head="头部" />
<h4> {this.props.data} </h4>
<ul>
{listItem}
</ul>
</Fragment>
);
}
}
ReactDOM.render( <App data='Hello World!'>, document.getElementById('app') );react 事件和表单数据绑定
import React, { Fragment } from 'react';
import ReactDOM from 'react-dom';
class ListContent extends React.Component{
constructor(props){
super(props);
}
ContentChange(e){
this.props.conChange(e.target)
}
render(){
return (
<li>
<input type='checkbox' value={this.props.index} onChange={this.ContentChange.bind(this)}>
{this.props.content}
{this.props.status ? <span>已完成</span> : <span>未完成</span>}
</li>
);
}
}
class ListMap extends React.Component{
constructor(props){
super(props);
this.Change = this.Change.bind(this);
}
Change(e){
this.props
}
render(){
return (
<ul>
this.props.listData.map((item, index) =>
<ListContent key={index} index={index} conChange={this.Change} content={item.content} status={item.status} />
);
</ul>
);
}
}
class App extends React.Component{
constructor(props){
super(props);
this.state = {
todos:[
{action:'起床',status:true},
{action:'刷牙',status:true},
{action:'吃饭',status:true},
{action:'工作',status:false},
{action:'总结',status:false}
]
};
this.appChange = this.appChange.bind(this);
}
appChange(e){
const index = e.index;
if(e.type=='checkbox' && e.checked){
this.state.todos[index].status = true;
const list = this.state.todos;
this.setState({
list
});
}else if(e.type=='checkbox' && !e.checked){
this.state.todos[index].status = false;
const list = this.state.todos;
this.setState({
list
});
}
}
render(){
return (
<Fragment>
<ListMap listData={this.state.todos} listChange={this.appChange} />
</Fragment>
);
}
}
ReactDOM.render(<App/>, document.getElementById('app'));以上就是react的基础入门操作,作为react的基础入门者,如有什么地方不对,欢迎大家拍砖补充。
关于webapck的配置后边再补充吧,今天就到这里。