react的render函数
很多时候我们都认为react
就是render
大法,也确实是,每次我们都是通过render
来重新渲染页面,我们来看render
的例子:
render() {
//JSX 语法
// {}
let helloWorld = 'yuxi';
// array
return (
<span>
<div className="App">
helloWorld,{helloWorld};
</div>
<div>
<States disable={false}
handShow={this.handShow}>
<span>hello world</span>
<span>hello yuxi</span>
<span>hello xiaoyu</span>
</States>
</div>
</span>
);
}
需要注意的是:render
应该只做页面展示和渲染,不应该有构造函数,回调函数,声明周期等。
react的state状态
state
是react
的状态管理,react
是单向数据流的,当我们需要对数据做改变的时候应该是:
constructor() {
super();
console.log('this is constructor....')
this.state = {
disable:false,
}
}
handClick = () => this.setState(
{
disable: !this.state.disable
}
)
react的props属性
当我们需要把父组件的数据或者函数传递给子组件的时候,我们一般都使用props
,我们来看一个例子:
传递给子组件:
<States disable={false}
handShow={this.handShow}>
<span>hello world</span>
<span>hello yuxi</span>
<span>hello xiaoyu</span>
</States>
子组件获取:
let args = this.props.disable;
我们再来比较一下react
和props
,到底什么时候用哪个呢?
简单来理解:
- 如果需要改变数据就使用:
state
- 如果需要传递数据就使用:
props
有一篇文章写得比较好:ReactJS: Props vs. State
react的声明周期
react
常用的声明周期有:
- constructor 构造函数
- componentWillMount
- componentDidMount
- componentWillUpdate
- componentDidUpdate
- componentWillUnmount
总的来说我们常用的就是:
constructor,componentWillMount,componentDidMount
来看一个简单例子:
import React, { Component } from 'react'
export class States extends Component {
constructor() {
super();
console.log('this is constructor....')
this.state = {
disable:false,
}
}
handClick = () => this.setState(
{
disable: !this.state.disable
}
)
componentWillMount() {
console.log('this is will mount')
}
componentDidMount() {
console.log('this is did mount');
}
componentWillUpdate() {
console.log('this is will update');
}
componentDidUpdate() {
console.log('this is did update');
}
handShow = () => {
let args = this.state.disable;
this.props.handShow(args);
}
handFocus = () => {
this.refs.myFocus.focus();
}
render() {
// state practise
// set this.props.children
// operate virtral DOM
let args = this.props.children;
let DOME = React.Children.map(args,(child) => {
return <li>{child}</li>
});
console.log(DOME)
return (
<div>
<input type="text" disabled={this.state.disable}></input>
<button onClick={this.handClick}> click me</button>
<button onClick={this.handShow}>show</button>
<ol>
{DOME}
</ol>
<input type="text" ref='myFocus'></input>
<button onClick={this.handFocus}> focus</button>
</div>
)
}
}
export default States