周末在家没什么事情,再次学习下React,以前自学过一段时间,后来放弃了,现在重新拿起来玩玩。
首先是再次在ubuntu上安装下开发工具
开发环境
1,下载下现在比较新的yarn,facebook推出的新的包管理工具,当然你也可以用npm 或者cnpm,具体上网搜索下
2,安傻瓜式的react官方脚手架,create-react-app.
yarn add global create-react-app
//or use the npm
npm install -g create-react-app
3 ,生成项目
cd js_workspace
create-react-app hello-react && cd hello-react
**Note** 这里注意了,hello-react代表项目名称和目录名称,作为java程序呀,习惯性的敲helloReact。就会出现名称不合法的问题
4,等待安装完成后,用visual studio code 打开目录
5 试着运行项目,在浏览器里查看效果,如果可以看到转动的logo。就ok了啊,启动命令如下,记得在hello-ract目录下运行哦
yarn start
//or
yarn run start
目录结构
![](https://img.haomeiwen.com/i3015497/009565a828d8f993.png)
开始正是开撸代码
首先在src目录下创建目录app1,其实就是为了把自己学习练手的无用代码,垃圾分类存放
cd <project_root>
mkdir -p src/app1
touch src/app1/demo.js
写入如下的内容
import React, { Component } from 'react';//import the required package from React
import PropTypes from 'prop-types'//now the PropTypes is moved to a seperate package
//创建文本框
class HelloMessage extends Component {
render() {
return (<h2>{this.props.message}</h2>);
}
}
//限制传入的参数的类型,如果参数类型部队,可以有warning提示,注意命令行
HelloMessage.propTypes = {
message: PropTypes.string,
}
HelloMessage.defaultProps = {
message: "default message",
}
//文本输入框,可以在编辑和只读之间切换
class TextBox extends Component {
constructor(props) {
super(props);
this.state = {
isEditing: false,
};
//注意,这边需要绑定this变量。React基于es6的代码不会自动绑定this
this.update = this.update.bind(this);
this.edit = this.edit.bind(this);
}
update() {
this.props.update(this.refs.messageTextBox.value);
this.setState({
isEditing: false,
});
}
edit() {
this.setState({
isEditing: true
});
}
render() {
return (
<div>
{this.props.label}<br />
<input type="text" ref="messageTextBox"
disabled={!this.state.isEditing} />
{
this.state.isEditing ?
<button onClick={this.update}>Update</button>
:
<button onClick={this.edit}>Edit</button>
}
</div>);
}
}
TextBox.propTypes = {
label: PropTypes.string.isRequired,
update: PropTypes.func.isRequired,//update是个function,
};
//外部容器component
export default class HelloReact extends Component {
constructor(props) {
super(props);
this.state = {
firstName: 'Hunter',
lastName: 'xue',
};
// this.update = this.update.bind(this);
}
update(key, value) {
var newState = {};
newState[key] = value;
//这里只要填写修改的属性,setState会进行merge
this.setState(newState);
}
render() {
return (
<div>
<HelloMessage message={'Hello ' + this.state.firstName + ' ' + this.state.lastName}>
</HelloMessage>
<TextBox label="First Name" update={this.update.bind(this, "firstName")}></TextBox>
<TextBox label="Last Name" update={this.update.bind(this, "lastName")}></TextBox>
</div>
);
}
}
因为这回是第二次学习,所以跳过了不少的内容,基础的react概念,读者可以从官网上获得,本人也加入了部分的注释
这里大体的逻辑就是,构建一个页面,里面有两个输入框和一个文本框,当任何一个输入框完成输入,并且点击update后,文本框的内容发生联动更新。其实就是个简单的事件处理
最后在index.js里修改下引用,读取我们新添加的component
import React from 'react';
import ReactDOM from 'react-dom';
import HelloReact from './app1/demo';
import './index.css';
ReactDOM.render(
<HelloReact />,
document.getElementById('root')
);
效果图
![](https://img.haomeiwen.com/i3015497/b3e1f32f647fffae.png)
网友评论