需求:电脑Computer组件,包含Screen组件和按钮button。
- Computer组件:有状态status:on和off。
- Screen组件:有props.showContent属性,接收传入值,如无默认“哈哈哈默认值”。显示一个文本,有onText和offText两个值,是电脑组件状态分别为on和off时的对应值。
- button按钮,可以修改Computer的status
class Screen extends Component {
render () {
return (
<div>
<div className='screen'>{this.props.showContent?this.props.showContent:'hahaha默认值'}</div>
</div>
)
}
}
class Computer extends Component {
constructor(){
super()
this.state={
status: 'on'
}
}
switchStatus(){
if(this.state.status==='on'){
this.setState({
status:'off'
})}
else{
this.setState({
status:'on'
})
}
}
render () {
const onText='我有电开着的'
const offText='我没电了关闭了'
return (
<div>
<button onClick={this.switchStatus.bind(this)}>开关</button>
<Screen showContent='我是传进来的props值'/>{this.state.status==='on'?onText:offText}
</div>
)
}
}
ReactDOM.render(<Computer/>,document.getElementById('root'))