Loading

如何简单实现一个react组件

函数式声明写react组件(推荐写法)


const Modal = > (props) {
    const { css, callback, type} = props
    //合并默认样式
    const css = {
        ...css, 
        defaultCss
    };
    return (
        <div>
            <span style={css}></span>   
        </div>
    )
}

export default Modal

ES6写react组件(是在你的组件涉及 react 的生命周期方法的时候采用这种写法)

import React from 'react'
import { render } from 'react-dom'

class SwitchButton extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      open: this.props.open
    }
  }

  handleClick => (event) {
    event.preventDefault();
    this.setState({ open: !this.state.open })
  }

  render() {
    let open = this.state.open,
      className = open ? 'switch-button open' : 'btn-switch'

    return (
      <label className={className} onClick={this.handleClick.bind(this)}>
        <input type="checkbox" checked={open}/>
      </label>
    )
  }
}

SwitchButton.defaultProps = {
  open: false
}

render(
  <SwitchButton />,
  document.getElementById('app')
)
posted @ 2017-07-04 09:53  lewiskycc  阅读(327)  评论(2编辑  收藏  举报