react组件传值

198 阅读1分钟
  1. 父组件传值给子组件
子组件通过props获取父组件对应属性名的数据
  1. 子组件传值给父组件
//父组件
import Home from "./home/home.js";
import React, { Component } from "react";
class element extends Component {
	constructor(props) {
            super(props);
                this.state = {
                    msg: "我是父组件的数据",
		};
	}
	setMsg = (pyload) => {
            console.log("接收到的数据",pyload);
	
	};
	render() {
            return (
               //这里传数据需要用到回调函数
              <div>
                 <Home fun={(pyload)=>{this.setMsg(pyload)}} />
                    <h2>Good to see you here.</h2>
              </div>
		);
	}
}
//子组件
import React, { Component } from "react";
class Home extends Component {
  constructor(props) {
    super(props);
    console.log(this.props);
	
  }
  setMsg=()=>{
   this.props.fun("我是子组件数据")
  };
  render() {
    return ( 
    <div>
    	<button onClick={this.setMsg}>按钮</button>
    </div>
    );
  }
}
  1. 跨级组件传值

React.createContext传值

使用 createContext创建Context对象,在顶层组件通过Provider提供数据, 在底层组件通过useContext函数获取数据。

import React, { createContext,useState,useContext } from "react";
// 通过 react 的 createContext 实现跨组件传值
const Context = createContext();

function DemoA() {
   // 通过 useContext 获取顶层的数据
   const count = useContext(Context);
   return (
       <div>
           DemoA
          顶层传递来的数据:{count}
           <DemoC />
       </div>
   );
}

function DemoC() {
   const count = useContext(Context);
   return <div>DemoC 
       顶层传递的数据:{count}
          </div>;
}

function ConText() {
   const [count,setCount] = useState(0);
   return (
   	// 使用 Provier 包裹最外层组件,利用 value 属性向n个子组件传递数据
       <Context.Provider value={count}>
           <div>
               <h1>context</h1>
               <button onClick={()=>setCount(count+1)}>{count}</button>
               <hr />
               <DemoA />
           </div>
       </Context.Provider>
   );
}