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 (
<div className='father'>
<Son fatherMsg={this.state.fatherMsg} />
</div>
)
}
}</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 (
<div className='Son'>
{this.state.fatherMsg}
{this.props.fatherMsg}
</div>
)
}
}</code></pre>
<h3>2.子组件数据传父组件:</h3>
<p>1、父组件在调用子组件时,传入一整个组件给子组件<code><Son father={ this } /></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 (
<div className='son'>
</div>
)
}
}</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) => {
this.setState({
sonMsg:msg
})
}
render(){
return (
<div className='father'>
{/* this is son data */}
{this.state.sonMsg}
<Son father={ this } />
</div>
)
}
}</code></pre>
<h3>3.子组件传自身组件给父组件:</h3>
<p>1.父组件在调用子组件时,通过ref属性,拿到整个子组件<code><Son ref='Son' /></code>;
2.父组件中通过<code>this.refs.Son</code>获取到一整个子组件实例(注意,要在DOM加载后才能获取);</p>