关于我们

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻公共列表

云南大王-React组件拆分与传值

发布时间:2020-04-13 00:00:00
组件拆分与组件之间的传值 父子组件的概念: 父组件通过属性的方式,向自组件传值 子组件通过this.props的属性,接收传递过来的值   父组件 src/TodoList.js import React,{Component,Fragment} from 'react'; import TodoItem from './TodoItem'; import './style.css'; class TodoList extends Component { constructor(props) { super(props); this.state = { inputVal:'', list:[] }; this.changeVal=this.changeVal.bind(this); this.addItem=this.addItem.bind(this); this.deleteItem=this.deleteItem.bind(this); } changeVal(e){ this.setState({ inputVal: e.target.value }); } addItem(e){ //按下回车键 if(e.keyCode===13 && e.target.value!==""){ const list=[...this.state.list,e.target.value] this.setState({ //list:list //对象的键值相同时,简写 list, inputVal:'' }) } } deleteItem(index){ const list=[...this.state.list]; list.splice(index,1);//从数组中删除指定index的数据 this.setState({ list }) } getList(){ return this.state.list.map((item,index)=>{ return ( ) }) } render(){ // 这是JS中的注释 return ( {/* 这是JSX中的注释 */}
    {this.getList()}
); } } export default TodoList;   自组件 TodoItem.js import React,{Component} from 'react'; class TodoItem extends Component{ constructor(props){ super(props); this.deleteItem=this.deleteItem.bind(this); } deleteItem(){ //调用父组件传递过来的方法 //this.props.deleteItem(this.props.index); //解构赋值写法 const {deleteItem,index}=this.props; deleteItem(index); } render(){ return
  • {this.props.item}
  • } } export default TodoItem;   效果图  

    /template/Home/Zkeys/PC/Static