react特点
- 用过ReactDOM.render(html,id)的方式渲染页面;
- 其中html是html字符串,多个html节点可以用()包含,里面可以使用js变量,js变量需要用{}包起来;id是挂载元素的实例,可以通过document.getElementById获取;
- 函数封装(组件):
function Clock(props) {
return (<div>{props.date}</div>)
}
<Clock date={new Date()}> - 除了函数外我们还可以创建一个React.Component 的 ES6 类,该类封装了要展示的元素,需要注意的是在 render() 方法中,需要使用 this.props 替换 props
JSX语法
- const element = <h1 className="class-name">Hello, world!</h1>;
- 推荐使用内联样式:
var myStyle = {
fontSize: 100,
color: '#FF0000'
};
ReactDOM.render(
<h1 style = {myStyle}>菜鸟教程</h1>,
document.getElementById('example')
); - JSX 允许在模板中插入数组,数组会自动展开所有成员:
var arr = [
<h1>菜鸟教程</h1>,
<h2>学的不仅是技术,更是梦想!</h2>,
];
ReactDOM.render(
<div>{arr}</div>,
document.getElementById('example')
);
组件:
- 可以使用命名函数function App(props)的方式构建组件,组件的变量用props.XXX显示;
- 也可使用class App extends React.Component方式定义组件如下:
组件的变量用this.props.XXX显示,组件内自己实现render函数,return的内容即是组件内容。
class App extends React.Component {
render(){
return (
<div>
<h1 style={{textAlign: 'center'}}>{this.props.title}</h1>
<Desc content={"好好学习,天天向上"}/>
</div>
);
}
}
状态State
- 在constructor里定义state状态, 如this.state = {date, new Date()};
- 更新状态使用setState,如this.setState('date', new Date());
- 通过调用 this.setState() ,React 知道状态已经改变,并再次调用 render() 方法来确定屏幕上应当显示什么
Props
- state 和 props 主要的区别在于 props 是不可变的,而 state 可以根据与用户交互来改变。这就是为什么有些容器组件需要定义 state 来更新和修改数据。 而子组件只能通过 props 来传递数据;
- 可以通过App.defaultProps的方式设置默认props;
- 我们可以在父组件中设置 state, 并通过在子组件上使用 props 将其传递到子组件上。在 render 函数中, 我们设置 name 和 site 来获取父组件传递过来的数据。
生命周期
- constructor:完成了React数据的初始化
- componentWillMount:在渲染前调用,在客户端也在服务端。
- componentDidMount: 在第一次渲染后调用,只在客户端。之后组件已经生成了对应的DOM结构,可以通过this.getDOMNode()来进行访问。 如果你想和其他JavaScript框架一起使用,可以在这个方法中调用setTimeout, setInterval或者发送AJAX请求等操作(防止异步操作阻塞UI)。
- componentWillReceiveProps:在组件接收到一个新的 prop (更新后)时被调用。这个方法在初始化render时不会被调用。
- shouldComponentUpdate:返回一个布尔值。在组件接收到新的props或者state时被调用。在初始化时或者使用forceUpdate时不被调用。
可以在你确认不需要更新组件时使用。 - componentWillUpdate:在组件接收到新的props或者state但还没有render时被调用。在初始化时不会被调用。
- componentDidUpdate:在组件完成更新后立即调用。在初始化时不会被调用。
- componentWillUnmount:在组件从 DOM 中移除之前立刻被调用。
事件处理
- <button onClick={activateLasers}>激活按钮</button>
- onClick={this.changeAge.bind(this)} 和 onClick={()=>this.changeAge()} 可以互换;
- 使用toggle = () => {}定义事件,则可以直接使用{this.toggle}方式触发事件;
- 推荐(event)=> this.toggle(event, 'a')方式调用函数;