React之配置组件的 props(两个实例)

React之配置组件的 props(两个实例)

React之配置组件的 props(两个实例)

> 这里要吐槽一下html模式下发布博客有问题,前面发了两遍都不能显示完全,很气。

1.第一个是点赞功能

import React, {Component} from 'react'
import ReactDOM from 'react-dom'
import './index.css'

//点赞功能

class LikeButton extends Component {
  constructor () {
    super()
    this.state = { isLiked: false }
  }

  handleClickOnLikeButton () {
    this.setState({
      isLiked: !this.state.isLiked
    })
  }

  render () {
    const likedText = this.props.likedText || '取消'
    const unlikedText = this.props.unlikedText || '点赞'
    return (
      <button onClick={this.handleClickOnLikeButton.bind(this)}>
        {this.state.isLiked ? likedText : unlikedText} ��
      </button>
    )
  }
}

class Index extends Component {
  render () {
    return (
      <div>
        <LikeButton likedText='已赞' unlikedText='赞' />
      </div>
    )
  }
}

  ReactDOM.render(
    <Index />,
    document.getElementById('root')
  )

2.第二个是胡子大哈的ScriptOJ上的例子

完成两个组件,电脑 Computer 和显示器 Screen。电脑有个 status 状态表示电脑现在是开还是关的,status 为 on 为开,status 为 off 为关,默认状态为 off。电脑有个按钮,点击可以*切换电脑的开关状态。显示器接受一个名为 showContent 的 props,显示器会把它内容显示出来。如果不传入 showContent,显示器显示 “无内容”。电脑包含显示器,当电脑状态为开的时候显示器显示“显示器亮了”,否则显示“显示器关了”。

class Computer extends Component{
  constructor(){
    super()
    this.state={status:'off'}//设置默认状态为'off'
  }
  clickButton(){
    this.setState(
      {status:this.state.status=='off'?'on':'off'}//改变status
      )
  }
  render(){
    return(
      <div>
        <button onClick={this.clickButton.bind(this)}>开关</button>
        <Screen showContent={this.state.status=='off'?'显示器关了':'显示器亮了'} />
      </div>
      )
  }
}

class Screen extends Component{
  static defaultProps={showContent:'无内容'} //设置静态显示内容
  render(){
    const showContent=this.props.showContent
    return(
      <div className='screen'>{showContent}</div>)
  }

  }
原文地址http://www.bieryun.com/2540.html