React父子组件传值方式一pros(简单记录)
只是简单记录下此种通信方式,后续还可通过redux等来实现组件通信 1、父组件给子组件通过props 父组件:
import React, { Component } from 'react'
import Header from './compoents/Header/index'
import List from './compoents/List'
import Footer from './compoents/Footer'
import './container.css'
export default class Container extends Component {
state = {
todos:[
{id:'001',name:'测试',done:true},
]
}
addTo = (todoObj)=>{
console.log("父组件接收到子组件传过来的值",todoObj)
}
render() {
const {todos} = this.state
return (
<div className='todo-container'>
<div className='todo-wrap'>
<Header addTo={this.addTo}/>
<List todos = {todos}/>
<Footer/>
</div>
</div>
)
}
}
2、子组件通过this.props接收值 子组件(此子组件接收父组件传过来的值):
import React, { Component } from 'react'
import Item from '../Item'
import './index.css'
export default class List extends Component {
render() {
const {todos} = this.props
console.log(todos)
return (
<ul className='todo-main'>
{
todos.map((todo,index)=>{
return <Item key={todo.id} {...todo}/>
})
}
</ul>
)
}
}
3、子组件给父组件传值,要求父给子通过props传的是一个函数,子组件通过调用父组件的函数达到给父传值的目的 子组件(此子组件向父组件传值):
import React, { Component } from 'react'
import './index.css'
export default class Header extends Component {
handleKeyUp = (event)=>{
const {key,target} = event
if(key!=='Enter') return
console.log(target.value,key);
this.props.addTo(target.value)
}
render() {
return (
<div className='to-header'>
<input onKeyUp={this.handleKeyUp} type="text" placeholder='测试输入接收传值'/>
</div>
)
}
}
传值成功
|