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;
  • 相关阅读:
    【2、koa】async和await(ES7)
    外部获取异步方法中的数据两种方式callback&Promise
    filter方法
    【ES6】let、var、const
    ubuntu下安装typora
    自我修养之产品思维与能力
    vue
    allure-pytest 测试报告分享给大家
    最近公司遇到了APR攻击,顺便了解一下知识
    Sybase数据库连接配置
  • 原文地址:https://www.cnblogs.com/linjiu0505/p/11887381.html
Copyright © 2011-2022 走看看