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;
  • 相关阅读:
    SpringBoot系列之切换log4j日志框架
    SpringBoot系列之日志框架使用教程
    SpringBoot系列之集成logback实现日志打印(篇二)
    源码学习系列之SpringBoot自动配置(篇二)
    SpringBoot系列之@Conditional注解用法简介
    7.Maven命令
    6.Maven构建过程的各个环节
    5.Maven坐标
    4.用IntelliJ IDEA 创建Maven Web
    3.用IntelliJ IDEA 创建Maven
  • 原文地址:https://www.cnblogs.com/linjiu0505/p/11887381.html
Copyright © 2011-2022 走看看