1、创立react我的项目
npx create-react-app my-app
(npx是 npm 5.2+ 附带的 package 运行工具)index.js
为入口文件
2、启动我的项目
npm start
3、jsx语法
能够利用{}写js表达式,如:{1 + 2}
不能写js语法if等,
4、函数this
函数要通过上面bind(this)绑定TodoList组件
this.handleBtnClick = this.handleBtnClick.bind(this)
5、父子组件传值
父组件通过属性传值;如:
content={item} index={index}
react根部只能有一个元素包裹,Fragment
为react
的片段,在页面中不显示;能够用于根部有两个或者多个元素
import React from "react";
import TodoItem from "./TodoItem";
class TodoList extends React.Component {
constructor(props) {
super(props);
this.state = {
list: [],
inputValue: "",
};
this.handleInputChange = this.handleInputChange.bind(this);
this.handleBtnClick = this.handleBtnClick.bind(this);
this.handleDlete = this.handleDlete.bind(this);
}
handleBtnClick() {
this.setState({
list: [...this.state.list, this.state.inputValue],
inputValue: "",
});
}
handleInputChange(e) {
this.setState({
inputValue: e.target.value,
});
}
handleDlete(index) {
const list = [...this.state.list];
list.splice(index, 1);
this.setState({
list,
});
}
getTodoItems() {
return this.state.list.map((item, index) => {
return (
<TodoItem
content={item}
key={index}
index={index}
delete={this.handleDlete}
></TodoItem>
);
});
}
render() {
return (
<React.Fragment>
<div>
<input
value={this.state.inputValue}
onChange={this.handleInputChange}
></input>
<button className="red-btn" style={{borderRadius:'2px',padding:'5px 10px'}} onClick={this.handleBtnClick}>add</button>
</div>
<ul>{this.getTodoItems()}</ul>
</React.Fragment>
);
}
}
export default TodoList;
子组件通过props接管;如
const { index } = this.props;
import React from "react";
class TodoItem extends React.Component {
constructor(props) {
super(props);
this.handleDelete = this.handleDelete.bind(this);
}
handleDelete() {
this.props.delete(this.props.index);
// const { delete , index } = this.props;
// delete index;
}
render() {
const { content } = this.props;
return <div onClick={this.handleDelete}>{content}</div>;
}
}
export default TodoItem;
发表回复