1.0.0 • Published 6 years ago
react.family.ink v1.0.0
JSX语法
JSX的属性值只能是“{}”括起来的表达式或者是引号〖 "" 或者 '' 不可以是 〗包起来的字符串
创建组件
React.createClass
const Button = React.createClass({
getDefaultProps(){
return {
color:'white',
content:'按钮'
}
},
render(){
const { color,content } = this.props;
return (<button class={`btn-${color}`}>{content}</button>);
}
})
ES6 class
import React,{Component} from 'react';
class Button extends Component{
constructor(props){
super(props);
}
static defaultProps = {
color:'white',
content:'按钮'
}
render(){
const { color,content } = this.props;
return (<button className={`btn-${color}`}>{content}</button>)
}
}
无状态函数
function Button({ color='blue',content='按钮' }){
return (
<button className={`btn-${color}`}>{content}</button>
)
}
JSX事件的写法
<button onClick={this.handleClick}>点击</button>
HTML事件的写法
<button onclick="handleClick()">点击</button>
HTML事件需要全部小写,如:onclick,且HTML的属性值只能是JavaScript代码字符串,而在JSX中,props的值则可以是仍以类型,在这里onClick的值是一个函数指针
自动绑定
在React组件中,每个方法的上下文都会指向该组件的实例,即自动绑定this为当前组件。但是在使用ES6的class或者纯函数的时候,这种绑定就不复存在了,需要我们手动绑定this。
**bind方法**
import React,{Component} from 'react';
class App extends Component{
handleClick(e,content){
console.log(e,content);
}
render(){
return <button onClick={this.handleClick.bind(this,'点击了...')}>按钮</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>)
}
}
1.0.0
6 years ago