组件通信分为几种:
父组件给子组件通信
子组件给父组件通信
兄弟组件通信
1.父组件给子组件通信
法一:
子组件页面:
import React from 'react';
export default class Child extends React.Component{
constructor(props) {
super(props)
}
render() {
return (
<div>
<h1>Hello,{this.props.name}</h1>
</div>
)
}
}
父组件页面:
<Child name='lala'/>
法二:
子组件页面:
import React from 'react';
import PropTypes from 'prop-types';
export default function Child({ name }) {
return <h1>Hello,{name}</h1>
}
Child.PropTypes = {
name:PropTypes.string.isRequired,
}
父组件页面:
<Child name='lala'/>
2.子组件给父组件通信:
子组件:
import React from 'react';
export default class Child extends React.Component{
constructor(props) {
super(props)
}
render() {
return (
<div>
哈哈哈哈,我是子组件
<button onClick={this.props.hideComponent}>隐藏子组件</button>
</div>
)
}
}
父组件:
import React from 'react';
import Child from './child';
export default class App extends React.Component{
constructor() {
super()
this.state = {
isShowChild:true
}
}
showComponent = () => {
this.setState({
isShowChild: true
})
}
hideComponent = () => {
this.setState({
isShowChild: false
})
}
render() {
return (
<div>
<button onClick={this.showComponent}>显示child组件</button>
{
this.state.isShowChild ? <Child hideComponent= {this.hideComponent}/> : null
}
</div>
)
}