JSX语法
JSX的属性值只能是“{}”括起来的表达式或者是引号〖 "" 或者 '' 不可以是 `` 〗包起来的字符串
创建组件
React.createClass
const Button = React
ES6 class
; { superprops; } static defaultProps = color:'white' content:'按钮' { const colorcontent = thisprops; return <button className=`btn-`>content</button> }
无状态函数
{ return <button className=`btn-`>content</button> }
JSX事件的写法
<button =>点击</button>
HTML事件的写法
点击
HTML事件需要全部小写,如:onclick,且HTML的属性值只能是JavaScript代码字符串,而在JSX中,props的值则可以是仍以类型,在这里onClick的值是一个函数指针
自动绑定
在React组件中,每个方法的上下文都会指向该组件的实例,即自动绑定this为当前组件。但是在使用ES6的class或者纯函数的时候,这种绑定就不复存在了,需要我们手动绑定this。
bind方法
; { console; } { return <button onClick=thishandleClick>按钮</button> }
双冒号语法 如果方法只绑定,不传参,可以使用stage0草案的双冒号语法,其作用与this.handleClick.bind(this)一样
import React,{Component} from 'react';class Button extends Component{ handleClick(e,content){ console.log(e.content); } render(){ return (<button onClick={::this.handleClick}>点击</button>) }}
构造器内声明 这种方式的好处是只需要进行一次绑定,而不需要每次调用时间监听器的时候都去执行绑定操作。
import React,{Component} from 'react';class Button extends Component{ constructor(props){ super(props); this.handleClick = this.handleClick.bind(this); } handleClick(e,content){ console.log(e,content); } render(){ return (<button onClick={this.handleClick}>点击</button>) }}