React组件通信
1.父传子:父组件通过props向子组件进行通信
父组件:
import React from 'react' import Son from './son' export default class Parent extends React.Component{ constructor(props){ super(props) this.text = 'hello world' } render() { return ( <div className="parent"> <Son text={this.text}></Son> </div> ) } }
子组件:
import React from 'react' export default class Son extends React.Component{ constructor(props){ super(props) } render() { return ( <div className="son"> {this.props.text} </div> ) } }
2.子传父:子组件通过调用父组件的方法
父组件:
import React from 'react' import Son from './son' export default class Parent extends React.Component{ constructor(props){ super(props) this.state = { name: 'hello world' } } _onChange(e) { this.setState({ name: e.target.value }) } render() { return ( <div className="parent"> <Son value={this.state.name} onChange={this._onChange.bind(this)} > </Son> <p>{this.state.name}</p> </div> ) } }
子组件:
import React from 'react' export default class Son extends React.Component{ constructor(props){ super(props) } _onChange(e) { this.props.onChange(e); } render() { return ( <div className="son"> <input type="text" value={this.props.value} onChange={this._onChange.bind(this)}/> </div> ) } }
3.兄弟组件通信:通过父组件作为中介传递
父组件:
import React from 'react' import SonA from './sonA' import SonB from './sonB' export default class Parent extends React.Component{ constructor(props){ super(props) this.state = { name: 'hello world' } } _onChange(e) { this.setState({ name: e.target.value }) } render() { return ( <div className="parent"> <SonA value={this.state.name} onChange={this._onChange.bind(this)} ></SonA> <SonB value={this.state.name}></SonB> </div> ) } }
子组件A:
import React from 'react' export default class SonA extends React.Component{ constructor(props){ super(props) } _onChange(e) { this.props.onChange(e); } render() { return ( <div className="sonA"> <input type="text" value={this.props.value} onChange={this._onChange.bind(this)}/> </div> ) } }
子组件B:
import React from 'react' export default class SonB extends React.Component{ constructor(props){ super(props) } render() { return ( <div className="sonB"> {this.props.value} </div> ) } }
浙公网安备 33010602011771号