关系如图所示,画的不好请见谅:
1、父传子app.js 传值
app.js传值 import React, { Component ,Fragment} from "react"; import One from "./components/one"; import Two from "./components/two"; export default class App extends Component { constructor() { super(); this.state = { message:"App组件" } } render() { let {message} = this.state; return ( <div className="app"> <h2>APP</h2> <One val={message}/> <Two/> </div> ) }
接受父组件app.js传过来的值 one.js
2、子传父
子组件two.js传值 import React,{Component}from "react"; export default class Two extends Component{ constructor(){ super(); this.state = { inputVal:"123", childVal:"" } render(){ let {childVal} = this.state; return ( <div className="two"> <h2>Two</h2> <button onClick={this.handle.bind(this)}>点击</button> <h3>接收到onone组件的值为:{childVal}</h3> </div> ) } handle(){ this.props.handleSend(this.state.inputVal); } } 父组件j接受app.js import React, { Component ,Fragment} from "react"; import One from "./components/one"; import Two from "./components/two"; export default class App extends Component { constructor() { super(); this.state = { message:"App组件", childVal:"" } } render() { let {message,childVal} = this.state; return ( <div className="app"> <h2>APP</h2> <h3>接收到子组件的值为:{childVal}</h3> <One val={message}/> <Two handleSend={this.handleSendFn.bind(this)}/> </div> ) } handleSendFn(val){ this.setState({ childVal:val }) } }
3、非父子
oneone.js 传值 import React,{Component}from "react"; import Observer from "../Observer"; export default class OneOne extends Component{ render(){ return ( <div className="oneone"> <h2>OneOne</h2> <button onClick={this.handleTwo.bind(this)}>传递给two</button> </div> ) } handleTwo(){ Observer.$emit("handleTo","oneone") } } two.js接收值 import React,{Component}from "react"; import Observer from "../Observer"; export default class Two extends Component{ constructor(){ super(); this.state = { inputVal:"123", childVal:"" } Observer.$on("handleTo",(val)=>{ console.log(val); this.setState({ childVal : val }) }) } render(){ let {childVal} = this.state; return ( <div className="two"> <h2>Two</h2> <button onClick={this.handle.bind(this)}>点击</button> <h3>接收到onone组件的值为:{childVal}</h3> </div> ) } handle(){ this.props.handleSend(this.state.inputVal); } }
总结一下:
原文:https://www.cnblogs.com/ray123/p/10915249.html