react父子组件传值

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 (
      
); } }

子组件接收,渲染页面

import React, { Component } from 'react'
import Center from './index.module.css'
export default class index extends Component {
  render() {
    let {todos} =this.props;
    return (
      
    {todos.map((i)=>{ return (
  • {i.name}
  • ) })}
) } }

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 (
      
); } }

子组件通过父组件传过来的函数,在合适的时机传给,父元素函数接收的data上

import React, { Component } from 'react'
import Header from './index.module.css'
export default class index extends Component {
  render() {
    return (
      
) } // 回车响应 keyCode=(e)=>{ if(e.keyCode===13){ this.props.a(e.target.value) } } }

你可能感兴趣的:(react.js,javascript,前端)