react 父子传值_react 父子传值,子组件修改父组件的state数据

话不多说直接来看代码吧,这次做的是个简单的增删功能,父组件在input输入框内输入的内容点击提交时要通过子组件作为列表展示在下方,点击任一项则删除相应列表项

index.js,作为入口文件,先将父组件引进来import React from 'react';

import ReactDom,{render} from 'react-dom';

import TodoList from './TodoList';//自己的组件,作为父组件

render(,window.root);

TodoList.js作为本次实例的父组件

1、实现父子传值,通过父组件引用子组件的时候通过属性的方式传递给子组件import React,{Component,Fragement} from 'react';

import TodoItem from './TodoItem';//子组件

class TodoList extends Component{

constructor(props){

super(props);

this.state={

inputValue:"",

list:[]

}

}

render(){

return(

onChange={(e)=>{

this.setState({

inputValue = e.target.value

})

}}

/>

{

this.setState({

list:[...this.state.list,this.state.inputValue]

})

}}>提交

{

this.state.list.map((item,index)=>{

return(

content = {item}

index = {index}

/>

)

})

}

)

}

}

export default TodoList;

TodoItem.js作为子组件,父组件已经将content和index传过来,子组件需要接收并展示,子组件通过this.props.属性名进行接收import React from 'react';

class TodoItem extends React.Component{

constructor(props){

super(props);

}

render(){

return(

{this.props.content}

)

}

}

2、通过子组件修改父组件的值

父组件 TodoList.jsimport React,{Component,Fragement} from 'react';

import TodoItem from './TodoItem';

class TodoList extends Component{

constructor(props){

super(props);

this.state = {

inputValue = "",

list:[]

}

}

render(){

return(

{

this.setState({

inputValue : e.target.value

})

}}/>

{

this.setState({

list:[...this.state.list,this.state.inputValue]

})

}}>提交

{

this.state.list.map((item,index)=>{

content = {item}

index = {index}

deleItem = {this.deleItemClick.bind(this)}

/>

})

}

)

}

//删除列表项内容的具体逻辑,通过属性传递给子组件,注意需要将函数的this始终指向父组件

deleItemClick(index){

let list = [...this.state.list];

list.splice(index,1);

this.setState({

list:list

})

}

}

export default TodoList

子组件TodoItem.jsimport React,{Component} from 'react';

class TodoItem extends Component{

constructor(props){

super(props);

render(){

return(

(this.props.deleItem(this.props.index))

{this.props.content}

)

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值