React pass value between split components to those

First, install

# Global installation
npm install -g create-react-app
# Build a My - App project
create-react-app my-app
# React to start compiling the current project and automatically open HTTP: // localhost: 3000 / 
npm RUN Start

Second, the components of father and son

Parent component TodoList.js

import React, { Fragment, Component } from 'react';
import "./index.css";
import ToDoItem from "./ToDoItem";
class TodoList extends Component{
  constructor(props){
    super(props);
    this.state={
      inputValue:"",
      list:[]
    }
  }
  // monitor form change 
  onChangeValue (E) {
     the this .setState ({
      inputValue:e.target.value
    })
  }
  submitValue(){
    this.setState({
      list:[...this.state.list,this.state.inputValue],
      inputValue:""
    })
  }
  // delete the list 
  deleteValue (index) {
    const list=[...this.state.list];
    list.splice(index,1)
    this.setState({
      list:list
    })
  }
  render(){
    return (
      <Fragment>
        <Label htmlFor = "input"> Please enter your </ label>
        <input id="input" className="input" value={this.state.inputValue} onChange={this.onChangeValue.bind(this)}></input>
        <button onClick={this.submitValue.bind(this)}>提交</button>
        <ul>
          {
            this.state.list.map((item,index)=>{
              return <ToDoItem key={index} content={item} index={index} deleteValue={this.deleteValue.bind(this)}/>
            })
          }
        </ul>
      </Fragment>
    );
  }
}
export default TodoList;

There are two components of the parent state properties are inputValue, list, by the parent component content attribute on the tag, index, deleteValue methods to transfer data and subassemblies.

Subassemblies ToDoItem.js

import React,{Component} from 'react';
class ToDoItem extends Component{
  constructor(props){
    super(props);
    this.deleteItem=this.deleteItem.bind(this)
  }
  deleteItem(){
    this.props.deleteValue(this.props.index)
  }
  render(){
    return <div onClick={this.deleteItem}>{this.props.content}</div>
  }
}
export default ToDoItem;

ToDoItem subassembly, if you want to get the properties of the parent component inside, it is need to pass through the props. By {this.props.content}, {this.props.index} to get inside the parent component data.

Parent component subassembly to call a method to change the data in the parent component by {this.props.deleteValue} call parent element method, transfer method of the parent component required to bind this point

Guess you like

Origin www.cnblogs.com/zhanglichun/p/12198616.html
Recommended