React拆分组件与组件之间传值

一、安装

# 全局安装
npm install -g create-react-app
# 构建一个my-app的项目
create-react-app my-app
# 启动编译当前的React项目,并自动打开 http://localhost:3000/
npm run start

二、父子组件

父组件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:[]
    }
  }
  // 监听表单变化
  onChangeValue(e){
    this.setState({
      inputValue:e.target.value
    })
  }
  submitValue(){
    this.setState({
      list:[...this.state.list,this.state.inputValue],
      inputValue:""
    })
  }
  // 删除列表
  deleteValue(index){
    const list=[...this.state.list];
    list.splice(index,1)
    this.setState({
      list:list
    })
  }
  render(){
    return (
      <Fragment>
        <label htmlFor="input">请输入内容</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;

父组件state里有两个属性,分别是inputValue、list,父组件通过标签上的属性content、index、deleteValue向子组件传递数据和方法。

子组件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中,如果想拿到父组件里面的属性,就需要通过props传递。通过{this.props.content}、{this.props.index}拿到父组件里面的数据。

子组件要调用父组件的方法,去改变父组件的数据,通过{this.props.deleteValue}调用父组件的方法,父组件传递的方法需绑定this指向

猜你喜欢

转载自www.cnblogs.com/zhanglichun/p/12198616.html