React父子组件传值

(一)父组件向子组件传值:

              父组件向子组件传递内容,靠属性的形式传递。

 

{/*父组件*/}
import React,{Component,Fragment} from 'react' import Item from './item' import './style.css' class ItemList extends Component{ constructor(props){ super(props) this.state = { inputValue: '', list: ['1111','2222'] } } render () { return ( <Fragment> <div> <label htmlFor='addService'>项目名称</label> <input id='addService' className='input' value={this.state.inputValue} onChange={this.inputChange.bind(this)} /> <button onClick={this.addItem.bind(this)}> 添加项目</button></div> <ul> { this.state.list.map((item,index)=>{ return ( <Item content={item} key={index+item} index={index} deleteItem={this.deleteItem.bind(this)} /> ) }) } </ul> </Fragment> ) } inputChange(e){ console.log(e.target.value); this.setState({ inputValue: e.target.value }) } addItem(){ this.setState({ list: [...this.state.list,this.state.inputValue], inputValue: '' }) } deleteItem(index,e){ console.log(index,111,e) let list = this.state.list list.splice(index,1) this.setState({ list: list }) } } export default ItemList

(二)子组件通过props接收父组件传过来的值,子组件用props去触发父组件的方法

{/*子组件*/}
import React, { Component } from 'react';
class Item extends Component {
    constructor(props) {
        super(props);
        this.handleClick=this.handleClick.bind(this)
    }
    render() { 
        return ( 
            <li onClick={this.handleClick}>
                {this.props.content}
            </li>
         );
    }
    handleClick(){
        console.log(this.props.index)
        this.props.deleteItem(this.props.index)
    }
}
 
export default Item;
原文地址:https://www.cnblogs.com/linjiu0505/p/11887381.html