3.React中組件值傳遞的形象理解

代碼以下

父組件css

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

複製代碼

子組件代碼以下react

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中經過屬性去獲取值進行顯示,若是是碰到方法,那麼也是經過屬性去調用這個方法,可是這個方法的執行倒是在父組件中 git

WiHongNoteBookgithub

相關文章
相關標籤/搜索