react脚手架create-react-app安装:

npm install -g create-react-app

建立项目:

create-react-app my-app

cd my-app 

npm run start

react 组件的定义:

import React,{Component} from 'react'
class TodoItem extends Component{
constructor (props){
super(props)
this.handleClick = this.handleClick.bind(this)
}
render (){
return (
<div onClick={this.handleClick}>{this.props.content}</div>
)
}
handleClick () {
this.props.deleteItem(this.props.index)
}

}
在这个
TodoItem件中定义的方法在constructor函数中定义,而且this要重新绑定,这样就可以在onClick事件中就能直接使用,同时事件要大写,如onClick、onChange等等定义
编写TodoList组件:
import React,{Component,Fragment} from 'react'
import './style.css'
import TodoItem from './TodoItem'
class TodoList extends Component{
constructor (props) {
super(props)
this.state = {
inputValue:'' ,
list:[]
}
this.handleInputChange = this.handleInputChange.bind(this)//方法在这里定义下面就不用bind(this)了直接引用方法
this.handlBtnClick = this.handlBtnClick.bind(this)

}
render () {
return (<Fragment> // render return必须有div抱起来,react提供了Fragment这样检查元素就不会显示该标签如果用div包着的会显示div
 

<div>
{/*下面是input框*/}
<label htmlFor='arear'>输入内容</label> //label for在react会认为是for循环,因此对于label for 用htmlFor这样点击label时候,input标签会被凝聚焦点
<input value = {this.state.inputValue}
id='arear'
onChange = {this.handleInputChange}
className= 'input'// class 在jsx中要写成className
/>
<button onClick = {this.handlBtnClick}>提交</button>
</div>
<ul>
{
this.state.list.map((item,index) => {
return (
<div>
<TodoItem content = {item}
index = {index}
deleteItem = {this.handleDelete.bind(this)} //给子组件传递方法需要bind(this)这样在子组件中就可以调用父组件的方法handleDelete
/>
</div> )
})
}
</ul>
</Fragment>
)
}
handleInputChange (e) {
const value = e.target.value //这里是异步的需要定义一个变量接收e.target.value这样就不会报错了
this.setState((e) =>({
inputValue:value //这里react旧版的用this.setState({
inputValue:value
})现在新版的用左面的this.setState()接收一个函数而不是对象了

}))

}
handlBtnClick () {
this.setState({
list:[...this.state.list,this.state.inputValue],
inputValue:''
})
}
handleDelete (index) {
const list = [...this.state.list]; // react中改变state中的属性用this.setState
list.splice(index,1);
this.setState({
list
})
//console.log(index)
}

}
export default TodoList // 编写好的组件需要export default 出去
子组件TodoItem
import React,{Component} from 'react'
class TodoItem extends Component{
constructor (props){
super(props)
this.handleClick = this.handleClick.bind(this)
}
render (){const content = this.props.content //通过父组件获取的content
return (
<div onClick={this.handleClick}>{content}</div>
)
}
handleClick () {
this.props.deleteItem(this.props.index)//从父组件中获取的index和方法
}

}
export default TodoItem

通过这个例子,父传子数据及方法是传给子组件,子组件通过this.props接收父组件的数据和方法,但是父组件给子组件传递方法的时候,要bind(this)