# React 实践

# 实践原则

state设计原则:尽可能的让大多数的组件都是无状态的

常见的做法是创建尽可能多的无状态组件,这些组件唯一关心的事情就是渲染数据,而在这些组件的外层,应该有一个包含state的父级别的组件。这个组件用来处理各种事情,交流逻辑,修改state

# How to write a component in React using ES6(使用ES6的语法写组件)

import React from 'react'
import ReactDOM from 'react-dom'

class App extends React.Component {

  constructor() {
    super()
    this.state = {}
  }
  
  render() {
    return (
      <div>
        Hello {this.props.name}
        <input type="text" onChange={this.update.bind(this)}/>
      </div>)
  }
}

App.propTypes = {
  name: React.PropTypes.string
}

App.defaultProps = {
  name: 'welcome to react'
}

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

# Bind a method in React(react中绑定方法名)

React in es6 可以在构造函数中绑定一个方法

import React from 'react'
import ReactDOM from 'react-dom'

class App extends React.Component {

  constructor() {
    super()
    this.state = {}
    this.update = this.update.bind(this)
  }

  update() {
    console.log(arguments)
    console.log(this)
  }

  render() {
    return (
      <div>
        Hello {this.props.name}
        <input type="text" onChange={this.update}/>
      </div>)
  }
}

App.propTypes = {
  name: React.PropTypes.string
}

App.defaultProps = {
  name: 'welcome to react'
}

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

# 获取输入框的值ref

大多数情况下是不需要操作DOM的方式去更新UI,应该使用setState的来重新渲染UI,但是,有一种情况确实需要访问一些DOM结构,(例如表单的值),那么就可以采用refs这种方式来获取DOM节点。

addName(e){
   var value = this.refs.name.value;
}

render(){
    return (
       <div> 
          姓名:<input text="txt" ref="name"/>
          <button onClick={this.addName}输入姓名</button>
       </div>
    )
}

# 如果存在多个不同的相同组件时,为了区分使用refs,如何取值

ReactDOM.findDOMNode(this.refs.red).value

	<Slider ref="red" update={this.update}/>
	<Slider ref="green" update={this.update}/>
	<Slider ref="blue" update={this.update}/>

Tips: 如果存在深层次的调用可能存在this.refs.red.refs.xx的用法

# 如何加入project的favicon.ico

背景: 分析: 解决:使用此库:https://github.com/cezary/react-favicon

# 如何设置一个div可编辑

背景: 为了实现一个可编辑的输入块,不想使用textarea 分析:使用div 解决:给div加上contentEditable属性

 <div ref="content" id="item-show" className="item-show" onClick={this.focus} onInput={::this.saveDate}
             contentEditable={this.props.isEditing}
             suppressContentEditableWarning={true}>
 </div>

# 命名原则

We recommend naming props from the component’s own point of view rather than the context in which it is being used.

陕ICP备20004732号-3