目录
- 实现一个简单的todolist
- JSX编码细节
github地址:https://github.com/cindygogogo/studyReact/tree/master/todolist
实现一个简单的todolist
1.create-react-app
npx create-react-app my-app
cd my-app
npm start
当执行npm start的时候:我遇到了入下遇到报错信息
It is likely not a bug in Create React App, but something you need to fix locally.
The react-scripts package provided by Create React App requires a dependency:
"webpack": "4.XX.XX"
Don't try to install it manually: your package manager does it automatically.
However, a different version of webpack was detected higher up in the tree:
解决办法如下:
卸载webpack、webpack-cli
npm un webpack
npm un webpack-cli
npm un webpack-dev-server
安装控制台提示的版本号
npm i webpack@4.xx.xx
npm i webpack-cli
npm i webpack-dev-server@3.xx.xx
解决create-react-app 后 npm start 中出现 的webpack版本问题和webpack-dev-server的版本问题
2.简化项目工程结构(也可以直接跳过)
3.在index.js中引入Todolist组件
import React from 'react';
import ReactDOM from 'react-dom';
// all in js
import Todolist from './Todolist';
ReactDOM.render(<Todolist />, document.getElementById('root'));
4.todolist 实现代码
import React, {Fragment, Component} from 'react';
// Fragment 占位符 消除最外层div
class Todolist extends React.Component{
constructor (props) {
super(props)
this.state = {
inputValue: '',
list: []
}
}
render() {
return (
<Fragment>
<div>
<input value={this.state.inputValue}
onChange={this.handleInputChange.bind(this)}/>
<button onClick={this.handleBtnClick.bind(this)}>提交</button>
<ul>
{
this.state.list.map((item, index) => {
return <li
key={index}
onClick={this.handleItemDelete.bind(this, index)}>
{item}
</li>
})
}
</ul>
</div>
</Fragment>
);
}
handleInputChange(e) {
this.setState({
inputValue: e.target.value
})
}
handleBtnClick () {
this.setState({
list: [...this.state.list, this.state.inputValue],
inputValue: ''
})
}
handleItemDelete (index) {
const list = [...this.state.list]
list.splice(index, 1)
this.setState({
list: list,
})
}
}
export default Todolist;
JSX编码细节
1.在JSX的代码中编写注释
{/*第一种注释的写法*/}
{
//第二种注释的写法
}
2.使用className 代替 class
<input className="input">
3.动态渲染HTML
dangerouslySetInnerHTML={{__html: item}}
4.label使用for属性的时候,用htmlFor替换
<label htmlFor="insertArea">输入内容</label>
<input id="insertArea" />
(完)