父传子
.content{
width: 400px;
height: 400px;
background-color: skyblue;
display: none;
}
.content.active{
display: block;
}
class ParentCom extends React.Component {
constructor(props) {
super(props)
this.state = {
isActive: true
}
}
render() {
return (
<div>
<button onClick={this.changeShow}>控制子元素显示</button>
{}
<ChildCom isActive={this.state.isActive} />
</div>
)
}
changeShow = ()=> {
this.setState({
isActive: !this.state.isActive
})
}
}
class ChildCom extends React.Component {
render(){
let strClass = null
strClass = this.props.isActive ? " active" : ""
return(
<div className={"content"+strClass}>
我是子元素
</div>
)
}
}
ReactDOM.render(
<React.StrictMode>
<ParentCom />
</React.StrictMode>,
document.getElementById('root')
);
子传父
class ParentCom extends React.Component {
constructor(props) {
super(props)
this.state = {
childData: null
}
}
render() {
return (
<div>
<h1>子传父:{this.state.childData}</h1>
<ChildCom setChildData={this.setChildData}/>
</div>
)
}
setChildData = (data)=> {
this.setState({
childData: data
})
}
}
class ChildCom extends React.Component {
constructor(props) {
super(props)
this.state = {
msg: "hello"
}
}
render(){
return(
<div>
<button onClick={this.sendData}>传递msg到父元素</button>
</div>
)
}
sendData=()=>{
this.props.setChildData(this.state.msg)
}
}
ReactDOM.render(
<React.StrictMode>
<ParentCom />
</React.StrictMode>,
document.getElementById('root')
);