React组件间通信(父=>子)(子=>父)(子=>爷)(删除指定下标的数据)

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<meta http-equiv="X-UA-Compatible" content="ie=edge">

<title>Document</title>

</head>

<body>

<div id="box"></div>

</body>

<script src="js/react.js"></script>

<script src="js/react-dom.js"></script>

<script src="js/browser.min.js"></script>

<script type="text/babel">

//孙子

var ToDoItem=React.createClass({

Del:function(index){

console.log(index)

//把下标传递给爷爷

this.props.MyListDel(index)

},

render:function(){

return <li>

<button onClick={()=>{this.Del(this.props.MyIndex)}}>删除</button>

{/*接收父组件传来的值*/}

<span>{this.props.MyCounter}</span>

</li>

}

})

//父亲

var ToDoList=React.createClass({

render:function(){

return <ul>

{/* <ToDoItem></ToDoItem> 接收父组件传来的值再通过map遍历 然后把值MyCounter传递给子组件 MyListDel删除指定下标通过爷爷定义方法传递给孙子*/}

{this.props.MyList.map((value,index)=>{

return <ToDoItem key={index} MyCounter={value} MyListDel={this.props.myDel} MyIndex={index}></ToDoItem>

})}

</ul>

}

})

//父亲的兄弟

var ToDoInput=React.createClass({

myInput:function(){

this.props.myfanter(this.refs.MyValue.value)

},

render:function(){

return <div>

<h1>请输入字符</h1>

<input type="text" ref='MyValue'/>

<button onClick={this.myInput}>添加</button>

</div>

}

})

//爷爷

var ToDoBOx=React.createClass({

//1.1定义一个数组接收儿子传来数据

getInitialState:function(){

return {list:[]}

},

//1.父亲定义方法传给子组件

fanter:function(msg){

//1.2将儿子每次传递过来的值放入list

var text=this.state.list;

text.push(msg)

this.setState({list:text})

console.log(this.state.list)

},

DelList:function(index){

//根据孙子传递过来的值删除下标

var text=this.state.list

text.splice(index,1)

this.setState({list:text})

},

render:function(){

return <div>

<ToDoInput myfanter={this.fanter}></ToDoInput>

<ToDoList MyList={this.state.list} myDel={this.DelList}></ToDoList>

</div>

}

})

ReactDOM.render(<ToDoBOx></ToDoBOx>,document.getElementById('box'))

</script>

</html>

猜你喜欢

转载自blog.csdn.net/xuyulong1993/article/details/83002787