入门react

入门react,做一个输入框输入类内容点击按钮下面列表添加输入的内容,首先拆分为两个模块,一个是输入添加模块,一个是显示内容模块,

import React ,{ Component, Fragment} from 'react'
import TodoItem from './TodoItem'
import './style.css'

class TodoList extends Component {
constructor( props){
super( props);
this. state = {
inputVale: '',
list:[]
}
this. handleInputChange = this. handleInputChange. bind( this)
this. handleBtnClick = this. handleBtnClick. bind( this)
this. handleItemDelete = this. handleItemDelete. bind( this)
}
render(){
return(
< Fragment >
< div >
{ /* 下面是一个注释 */ }
< label htmlFor= "insertArea" >输入类容 </ label >
< input
id= "insertArea"
className= "input"
value= {this. state. inputVale }
onChange= {this. handleInputChange }
/>
< button onClick= {this. handleBtnClick } >提交 </ button >
</ div >
< ul >
{
this. getTodoItem()
// this.state.list.map((item,index)=>{
// return (
// <div>
// <TodoItem
// item={item}
// index={index}
// key={index}
// deleteItem={this.handleItemDelete}
// />
// </div>
// )
// })
}
</ ul >
</ Fragment >
)
}

getTodoItem(){
return this. state. list. map(( item, index) =>{
return (
< TodoItem
key= { index }
index= { index }
item= { item }
deleteItem= {this. handleItemDelete }
/>
)
})
}
handleInputChange( e){
const value = e. target. value
this. setState(() =>{
return{
inputVale:value
}
})
// this.setState({
// inputVale:e.target.value
// })
}
handleBtnClick(){
this. setState(( prevState) =>{
return{
list:[... prevState. list, prevState. inputVale],
inputVale: ''
}
})
// this.setState({
// list:[...this.state.list,this.state.inputVale],
// inputVale:''
// })
}
handleItemDelete( index){
// const list = [...this.state.list];
// list.splice(index,1)
this. setState(( prevState) =>{
const list = [... prevState. list]
list. splice( index, 1)
return{
list
}
})
// this.setState({
// list:list
// })
}
}


export default TodoList;

上面是输入添加某块,首先handleInputChange绑定输入的值,然后点击提交的时候我们在list里面添加输入的值,在render里面我们可以把循环展示的抽离出来当作这一个方法

然后在向子组件传值。

import React,{ Component} from 'react'
import PropTypes from 'prop-types'
class TodoItem extends Component{
constructor( props){
super( props)
this. handleClick = this. handleClick. bind( this)
}
render(){
const { item, test} = this. props
return (
< div onClick= {this. handleClick } >
{ test }-- { item }
</ div >
)
}
handleClick(){
const { deleteItem, index} = this. props
deleteItem( index)
// this.props.deleteItem(this.props.index)
}
}

TodoItem. propTypes = {
test:PropTypes. string. isRequired, //父组件必传必传
item:PropTypes. arrayOf( PropTypes. number, PropTypes. string), //字符串或者数字
deleteItem:PropTypes. func,
index:PropTypes. number
}
TodoItem. defaultProps ={
test: 'hello world' //没传就是hello world
}
export default TodoItem

子组件接受值,下面定义父组件传来的值的类型。关于删除,父组件向子组件传index,以及方法,子组件在方法里面传入index,父组件实现按方法。

子组件接收父组件的值本是this.props.item 这里写成const {item} = this.props是一样的 es6的解构赋值。

猜你喜欢

转载自blog.csdn.net/axibadexiang/article/details/80885737