引入
本来我是没想过总结这些东西的,会感觉比较入门。但是之前同学去腾讯面试问到了这个问题(react或vue的组件通信),我帮他整理,顺便写demo的过程中,会有一些新的体会,多总结还是有利于进步的呀。
父子组件
父 → 子
parent组件传给child组件,符合react的单向数据流理念,自上到下传递props。
// 父组件class Parent extends Component { constructor() { super(); this.state = { value: '', } } handleChange = e => { this.value = e.target.value; } handleClick = () => { this.setState({ value: this.value, }) } render() { return ( <div> 我是parent <input onChange={this.handleChange} /> <div className="button" onClick={this.handleClick}>通知</div> <div> <Child value={this.state.value} /> </div> </div> ); }}
// 子组件class Child extends Component { render() { const { value } = this.props; return ( <div> 我是Child,得到传下来的值:{value} </div> ); }}
父组件做的就是定义好 state ,定义好事件函数,input onChange 的时候,去缓存 value 值,然后点击 button 的时候,改变 state , 子组件只负责展示 value 。
子 → 父
child 组件通知 parent 组件, 主要是依靠 parent 传下来的 callback 函数执行,改变 parent 组件的状态,或者把 child 自己的 state 通知 parent 。分两种情况:
state 定义在 parent 组件
// parentclass Parent extends Component { constructor() { super(); this.state = { value: '', } } setValue = value => { this.setState({ value, }) } render() { return ( <div> <div>我是parent, Value是:{this.state.value}</div> <Child setValue={this.setValue} /> </div> ); }}
class Child extends Component { handleChange = e => { this.value = e.target.value; } handleClick = () => { const { setValue } = this.props; setValue(this.value); } render() { return ( <div> 我是Child <div className="card"> state 定义在 parent <input onChange={this.handleChange} /> <div className="button" onClick={this.handleClick}>通知</div> </div> </div> ); }}
parent 组件把改变 state 的 setValue 函数传给 child ,child 组件自己处理内部的状态(这里是表单的value值),当 child 组件分发消息的时候, 执行 parent 的 setValue 函数,从而改变了 parent 的 state,state发生变化, parent 组件执行 re-render 。
state 定义在 child 组件
// parentclass Parent extends Component { onChange = value => { console.log(value, '来自 child 的 value 变化'); } render() { return ( <div> <div>我是parent <Child onChange={this.onChange} /> </div> ); }}
新闻热点
疑难解答
图片精选