更新于:2017年8月30日11:29:21
零零碎碎
首字母大写
组件首字母要大写,React 会将小写开头的标签名认为是 HTML 原生标签
扩展属性
如果你已经有了个 props 对象,并且想在 JSX 中传递它,你可以使用 ... 作为扩展操作符来传递整个属性对象。下面两个组件是等效的:
当你构建通用容器时,扩展属性会非常有用。然而,这样做也可能让很多不相关的属性,传递到不需要它们的组件中使代码变得混乱。React建议你谨慎使用此语法。
ant-design-mobile
Create React App
| 
 | 
 | 
生命周期
1. 初始化过程
| 
 | 
 | 
2. 更新过程
| 
 | 
 | 
事件处理
- 使用 camelCase 模式 onClick
- 阻止默认事件 ev.preventDefault
- 事件的 this问题123456// 1. 使用 bind 绑定,优先使用该方式this.method = this.method.bind(this)// 2. 试验特性method = () => {}// 3. 性能问题onClick={() => this.method()}
Refs & DOM
如果可以通过声明式实现,则尽量避免使用 refs。
例如,不要在 Dialog 组件上直接暴露 open() 和 close() 方法,最好传递 isOpen 属性。
React 支持给任意组件添加特殊属性。ref 属性接受一个回调函数,它在组件被加载或卸载时会立即执行。
- 当给 HTML 元素添加 - ref属性时,- ref回调接收了底层的 DOM 元素作为参数。例如,下面的代码使用- ref回调来存储 DOM 节点的引用。1<input type="text" ref={(input) => { this.textInput = input; }} />
- 当 ref 属性用于使用 class 声明的自定义组件时,ref 的回调接收的是已经加载的 React 实例。 123456789101112class AutoFocusTextInput extends React.Component {componentDidMount() {this.textInput.focus();}render() {return (<CustomTextInputref={(input) => { this.textInput = input; }} />);}}- 需要注意的是,这种方法仅对 - class声明的- CustomTextInput有效123class CustomTextInput extends React.Component {// code here}
你不能在函数式组件上使用 ref 属性,因为它们没有实例
如果你想使用 ref,就像你想使用生命周期方法或者 state 一样,应该将其转换为 class 组件。
