与VUE比较
-
思路相同、语法糖有出入
父子间
-
父组件
import React, { Component } from 'react' import Chuancan from "./Chuancan" class App extends Component { //js的构造函数,由于其他任何函数执行 constructor(props) { super(props) //调用父类的构造函数,固定写法 this.state = { inputValue: 'aa', item: "0" } } render() { return ( <div> {/* 子组件 ,content传参值、toFather接收事件*/} <Chuancan content={this.state.item} toFather={this.fatherEvent.bind(this)} /> </div> ) } fatherEvent(v) { console.log(v) } } export default App;
-
子组件
import React, { Component } from 'react'; class Chuancan extends Component { state = { val: "222" } render() { return (<span onClick={this.childEvent.bind(this)}>父子传参{this.props.content}</span>); } childEvent() { {/* 接受和传参均需使用this.props*/} this.props.toFather(this.state.val); } } export default Chuancan;
兄弟间(改变兄弟组件的颜色,还是依靠父子通信)
-
子组件一
class Children1 extends Component{ constructor(props){ super(props); } handerClick(){ this.props.changeChild2Color('skyblue') } render(){ return( <div> <div>children1</div> <button onClick={(e)=>{this.handerClick(e)}}>改变children2背景</button> </div> ) } }
-
子组件二
class Children2 extends Component{ constructor(props){ super(props); } render(){ return( <div style={{background:this.props.bgcolor}}> <div>children2 背景色 {this.props.bgcolor}</div> </div> ) } }
-
父组件
class Father extends Component{ constructor(props){ super(props) this.state = { child2bgcolor:'pink' } } onchild2bgChange(color){ this.setState({ child2bgcolor:color }) } render(){ return( <div> <Children1 changeChild2Color={(color)=>{this.onchild2bgChange(color)}} /> <Children2 bgcolor={this.state.child2bgcolor} /> </div> ) } }
网友评论