React 父组件引用子组件并给子组件传递参数或方法,子组件通过props来获取父组件传递过来的参数,或者触发父组件传递过来的方法来给父组件传值
父组件:
import React, { Component } from 'react'
import B from './B'
export default class A extends Component {
state={
data:''
}
getData=(data)=>{
this.setState({data})
}
render() {
const {data} = this.state;
return (
<div>
<B type='传递参数' toMyChild={this.getData}/>
{data}
</div>
)
}
}
子组件:
import React, { Component } from 'react'
export default class B extends Component {
componentDidMount(){
const {toMyChild} = this.props;
toMyChild('to my father');
}
render() {
const {type} = this.props;
return (
<div>
{type}
</div>
)
}
}