标签:pre turn dex color his map tar mic load
1.Component组件拆分
将原来的列表拆分成一个子组件,形成父子组件(父组件:Xiao.js;子组件:XiaoItem.js)
拆分:
Xiao.js中:
XiaoItem.js中:
2.父子组件的传值
父组件向子组件传值,通过属性传值
如果我要删除一个元素,即子组件要向父组件传值
React不允许直接从子组件向父组件传值的
依然通过属性传递的方法,再调用父组件的deleteItem()方法进行删除
Xiao.js
import React, {Component, Fragment} from "react"; import ‘./style.css‘ import XiaoItem from "./XiaoItem"; class Xiao extends Component { //构造函数,所有数据写在state中,初始化,固定写法 constructor(props) { super(props); this.state = { inputValue:‘jsPang‘, list:[‘基础‘, ‘升级1‘] } } render() { return ( <Fragment> {/*第一次写注释*/} <div> <label htmlFor="jsPang">增加服务:</label> <input id="jsPang" className="input" value={this.state.inputValue} onChange={this.inputChange.bind(this)}/> <button onClick={this.addList.bind(this)}>增加</button> </div> <ul> {this.state.list.map((item,index)=>{ return ( <XiaoItem key={item+index} content={item} index={index} deleteItem={this.deleteItem.bind(this)} /> ) })} </ul> </Fragment> ); } inputChange(e){ this.setState({ inputValue: e.target.value }) } //增加列表 addList(e){ this.setState({ // ...表示扩展运算符,相当于list:[‘基础‘, ‘升级1‘, this.state.inputValue] list:[...this.state.list, this.state.inputValue], inputValue:‘‘ }) } // 删除列表项目 deleteItem(index){ console.log(index) // 声明局部list let list = this.state.list list.splice(index, 1) this.setState({ list:list }) } } //组件暴露,让外界引用 export default Xiao
XiaoItem.js
import React, {Component} from "react"; class XiaoItem extends Component{ constructor(props) { super(props); this.handleClick = this.handleClick.bind(this) } render() { return ( <li onClick={this.handleClick}>{this.props.content}</li> ) } handleClick(){ this.props.deleteItem(this.props.index) } } export default XiaoItem
两种绑定方法:
建议用下面这种方法:
标签:pre turn dex color his map tar mic load
原文地址:https://www.cnblogs.com/GumpYan/p/13207776.html