React 之脚手架和组件传参

这篇博客介绍了如何在Node.js环境下搭建React应用,详细阐述了组件传参的多种方式,包括父传子、子传父、兄弟组件通信、跨组件通信以及使用refs进行子传父操作和DOM元素交互。内容涵盖了React应用创建、Context API的使用以及refs的实践。
摘要由CSDN通过智能技术生成

nodejs 环境开发

ES7 React/Redux/GraphQL/React-Native snippets

创建 react 应用

方法①

 npx create-react-app appdome

方法②

npm i create-react-app -g
create-react-app appdome

降版本

npm i react@17.0.0 react-dom@17.0.0

清理目录结构
appdome
– public
index.html
– src
index.js 入口文件
app.js 根组件

运行

npm start 

组件传参

父传子

在父组件使用子组件的地方,定义属性传参
– 子组件中通过 props 接收参数,类组件需要 this.props.属性名,函数组件 props.属性名
– 传参类型:字符串… 基本数据类型、对象{}、函数 ()=>{}、jsx

App.js

import React, {
    Component } from 'react'
import Parent from './dome/Parent'

export default class App extends Component {
   
  render() {
   
    return (
      <div>
        <Parent/>
      </div>
    )
  }
}

Parent.js

import React,{
   Component} from 'react'
import Son from './Son'

export default class Parent extends Component {
   
    state = {
   
        msg:'The sound of a spring swallows dangerous stones',
        author:{
   
            name:'王维',
            identity:'poet'
        }
    }
  render(){
   
    return(
        <div>
            <h2>父传子</h2>
            <Son 
            msgs = {
   this.state.msg} 
            callback = {
   this.getMsg}
            />
        </div>
    )
  }
  getMsg = ()=> {
   
    console.log('>>The sound of the spring swallows dangerous stones, and the sun is cold and green.');
  }
}

Son.js

import React, {
    Component } from 'react'

export default class Son extends Component {
   
  render() {
   
    return (
      <div>
        <h2>Son组件</h2>
        <p>{
   this.props.msgs}</p>
        <button onClick = 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值