您的位置:首页 > Web前端 > React

【React】React.Component小结

2016-12-13 22:41 169 查看
React.Component 是一个抽象的Class,通常继承该类来构建自定义的Component。 Component可以将U分离成独立的碎片,有点类似于JavaScript的function,它接受一个任意的输入(props)并返回一个React element描述屏幕中的内容。

有两种方法构建Components

1 JavaScript函数

function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}

function App() {
return (
<div>
<Welcome name="Sara" />
<Welcome name="Cahal" />
<Welcome name="Edite" />
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);


注意: Component必须返回单个根元素,因而要用
将包住。

2 利用React.Component 创建

class Greeting extends React.Component {
constructor(props){
super(props);
this.state = {
color: props.initialColor
};

}
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}


必须包含render()方法

Component 生命周期

1 Mounting (挂载)

constructor() // 构造函数

componentWillMount()

render()

componentDidMount()

2 Updating

componentWillReceiveProps()

shouldComponentUpdate()

componentWillUpdate()

render()

componentDidUpdate()

3 Unmounting

-componentWillUnmount()

每个Component中有

setState()

通过this.setState({value: dddd}) 更新

Class Properties

-defaultProps

class CustomButton extends React.Component {
// ...
}

CustomButton.defaultProps = {
color: 'blue'
};


-displayName

string用来在调试中显示信息

-propTypes

class CustomButton extends React.Component {
// ...
}

CustomButton.propTypes = {
color: React.PropTypes.string
};


Instance Properties

props

<Greeting  initialColor='blue' />


state

存储一些数据信息,如果不在render()中使用,则最好不要放在state中。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息