zoukankan      html  css  js  c++  java
  • 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;
  • 相关阅读:
    移动开发 Native APP、Hybrid APP和Web APP介绍
    urllib与urllib2的学习总结(python2.7.X)
    fiddler及postman讲解
    接口测试基础
    UiAutomator2.0 和1.x 的区别
    adb shell am instrument 命令详解
    GT问题记录
    HDU 2492 Ping pong (树状数组)
    CF 567C Geometric Progression
    CF 545E Paths and Trees
  • 原文地址:https://www.cnblogs.com/linjiu0505/p/11887381.html
Copyright © 2011-2022 走看看