Legendary

李洋的学习笔记


react组件间信息传递

<h3>1.父组件数据传子组件:</h3> <pre><code>//父组件 import React from 'react' import Son from './components/Son' class Father extends React.Component{ constructor(props){ super(props) this.state = { fatherMsg:'this is father data' } } render(){ return ( &lt;div className='father'&gt; &lt;Son fatherMsg={this.state.fatherMsg} /&gt; &lt;/div&gt; ) } }</code></pre> <pre><code>//子组件 import React from 'react' export default class Son extends React.Component{ constructor(props){ super(props) this.state = { fatherMsg:this.props.fatherMsg } } render(){ return ( &lt;div className='Son'&gt; {this.state.fatherMsg} {this.props.fatherMsg} &lt;/div&gt; ) } }</code></pre> <h3>2.子组件数据传父组件:</h3> <p>1、父组件在调用子组件时,传入一整个组件给子组件<code>&lt;Son father={ this } /&gt;</code>; 2、父组件中定义一个方法getSonMsg(result, msg),用来获取子组件传来的值以及执行其他操作; 3、子组件在通过this.props来获取到一整个组件this.props.parent或者this.props[parent]</p> <pre><code>//子组件 import React from 'react' export default class Son extends React.Component{ constructor(props){ super(props) this.state = { sonMsg:'this is son data' } } ComponentDidMount(){ this.props.father.getSonMsg(this,this.state.sonMsg) } render(){ return ( &lt;div className='son'&gt; &lt;/div&gt; ) } }</code></pre> <pre><code>//父组件 import React from 'react' import Son from './components/Son' class Father extends React.Component{ constructor(props){ super(props) this.state = { sonMsg:'' } } getSonMsg = (result,msg) =&gt; { this.setState({ sonMsg:msg }) } render(){ return ( &lt;div className='father'&gt; {/* this is son data */} {this.state.sonMsg} &lt;Son father={ this } /&gt; &lt;/div&gt; ) } }</code></pre> <h3>3.子组件传自身组件给父组件:</h3> <p>1.父组件在调用子组件时,通过ref属性,拿到整个子组件<code>&lt;Son ref='Son' /&gt;</code>; 2.父组件中通过<code>this.refs.Son</code>获取到一整个子组件实例(注意,要在DOM加载后才能获取);</p>

页面列表

ITEM_HTML