实现效果如下:
首先 app.js 组件代码
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Btn from './button'
class App extends Component {
constructor(props){
super(props)
this.state={
display:false
}
}
render() {
return (
<div className="App" onClick={()=>{
this.setState({
display:false
})
}}>
<Btn display={this.state.display}/>
<Btn display={this.state.display}/>
<Btn display={this.state.display}/>
<Btn display={this.state.display}/>
</div>
);
}
}
ReactDOM.render(
<App/>,
document.getElementById('container')
);
其次是 button.js 组件代码
import React, { Component } from 'react';
class button extends Component {
constructor(props){
super(props)
this.state={
display: this.props.display
}
}
componentWillReceiveProps(nextProps){
if(this.state.display){
this.setState({
display: nextProps.display
})
}
}
render() {
return (
<div style={{height:100,width:'100%',margin:10,border:'1px solid #000'}}>
<button onClick={()=>{
this.setState({
display:!this.state.display
})
}}>
点击
</button>
<div style={{backgroundColor:'red',width:50,height:50,display:this.state.display?'block':'none'}}>
</div>
</div>
);
}
}
export default button;
核心就是是componentWillReceiveProps() 函数的用法