1.父组件向子组件传值使用props
import React,{Component} from 'react'
import Center from './components/Center'
export default class App extends Component {
state={
todos:[
{id:'001',name:'吃饭',done:true},
{id:'002',name:'睡觉',done:true},
{id:'003',name:'打代码',done:false},
]
}
render(){
return (
<div>
<Center todos={this.state.todos}/>
</div>
);
}
}
子组件接收,渲染页面
import React, { Component } from 'react'
import Center from './index.module.css'
export default class index extends Component {
render() {
let {todos} =this.props;
return (
<div>
<ul>
{todos.map((i)=>{
return (
<li key={i.id} className={Center.li}>
<div className={Center.leftBox}>
<input type="checkbox" defaultChecked={i.done}/>
<span>{i.name}</span>
</div>
<button>删除</button>
</li>
)
})}
</ul>
</div>
)
}
}
2.子组件向父组件传递参数
import React,{Component} from 'react'
// import Hello from './components/Hello'
import Header from './components/Header'
import Center from './components/Center'
import Foot from './components/Foot'
export default class App extends Component {
// ,data是子组件传给父组件的值
a=(data)=>{
console.log(data,'app')
}
render(){
return (
<div>
<Header a={this.a}/>
<Foot/>
</div>
);
}
}
子组件通过父组件传过来的函数,在合适的时机传给,父元素函数接收的data上
import React, { Component } from 'react'
import Header from './index.module.css'
export default class index extends Component {
render() {
return (
<div>
<input
className={Header.input}
type="text"
placeholder='请输入你的任务,按回车键确认'
onKeyUp={this.keyCode}></input>
</div>
)
}
// 回车响应
keyCode=(e)=>{
if(e.keyCode===13){
this.props.a(e.target.value)
}
}
}