Todolist. js (this is the parent component)
Import react, {component, fragment} from 'react '; import '. /style.css '; import todoitem from '. /todoitem '; Class todolist extends component {Constructor (props) {// The Super (props) function with the highest priority; this. state = {inputvalue: '', list: []} render () {return (<fragment> <Div >{/ * This is a todolist */} <label htmlfor = 'insertarea '> input content </label> <input id = "insertarea" classname = 'input' value = {This. state. inputvalue} onchange = {This. handleinputchange. BIND (this)}/> <button onclick = {This. handlebuttonclick. BIND (this)}> submit </button> </div> <ul> {// This Is A list} {This. state. list. map (item, index) =>{ return (<todoitem // This is a child component key = {index} Index = {index} item = {item} deleteitem = {This. handleitemdelt. BIND (this)}/>)} </ul> </fragment>);} handleinputchange (e) {This. setstate ({inputvalue: e.tar get. value})} handlebuttonclick (e) {This. setstate ({list :[... this. state. list, this. state. inputvalue], inputvalue: ''})} handleitemdelt (INDEX) {// immutable // State does not allow us to change the const list = [... this. state. LIST]; // list a copy of list. splice (index, 1); this. setstate ({list: List})} export default todolist;
Todoitem. js (child component)
import React ,{ Component } from ‘react‘;class TodoItem extends Component{ render(){ return (<li onClick={this.handleclick.bind(this)} dangerouslySetInnerHTML={{__html:this.props.item}} > </li>) } handleclick(){ this.props.deleteItem(this.props.index); }}export default TodoItem;
Summary:
1. How to Create a splitting component?
1. First create a todoitem, and then write a component according to the react component
2. Relationship between parent and child components
Todolist is a large component, and todoitem is a small component. In react development, react is a tree structure.
3. Transmission Mode of parent component to child component
You can pass data and methods to sub-components by using tags.
index={ index }
deleteItem={this.handleItemdelt.bind(this)}
4. How do child components receive the transfer method?
This. Props. XXX is used to receive data, for example, this. Props. item.
5. How can I change the data of the parent component when the child component calls the method of the parent component?
Directly call this. Props. method, and then bind the BIND (this) at this point of the parent component)
Sub-component: This. Props. deleteitem ()
Parent component: deleteitem = {This. handleitemdelt. BIND (this )}
React splitting component on Components