程式碼如下
父元件
import React, { Component } from 'react'
import './TodoList.css'
import TodoListItem from './TodoListItem'
export class TodoList extends Component {
constructor(props) {
super(props)
this.state = {
inputValue:'',
list:[]
}
}
render() {
return (
<div>
<input
className = 'input'
value = {this.state.inputValue}
onChange = {this.handleinputChange.bind(this)} ></input> <button onClick = {this.handleBtnClick.bind(this)}>提交</button>
<ul>
{this.state.list.map((item,index) =>{
return <TodoListItem
content = {item}
index = {index}
handleItemDelete = {this.handleItemDelete.bind(this)}></TodoListItem>
// return <li key= {index} onClick = {this.handleBtnDeleteClick.bind(this,index)}>{item}</li>
})}
</ul>
</div>
)
}
handleinputChange(params) {
this.setState({
inputValue:params.target.value
})
console.log(params.target.value);
}
handleBtnClick(params){
this.setState({
list:[...this.state.list,this.state.inputValue],
inputValue:''
})
}
handleItemDelete(params){
const list = [...this.state.list];
list.splice(params,1);
this.setState({
list:list
})
}
handleBtnDeleteClick(params){
const list = [...this.state.list];
list.splice(params,1);
console.log(params);
this.setState({
list:list
})
}
};
export default TodoList
複製程式碼
子元件程式碼如下
import React, { Component } from 'react'
export class TodoListItem 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.handleItemDelete(this.props.index)
}
}
export default TodoListItem
複製程式碼
說明
父元件通過給子元件的屬性傳值,包括把內容顯示的值以及index還有方法都通過屬性傳到子元件中,子元件在自身div中通過屬性去獲取值進行顯示,如果是碰到方法,那麼也是通過屬性去呼叫這個方法,但是這個方法的執行卻是在父元件中