一、1、npm 默认配置成淘宝镜像 npm config set registry https://registry.npm.taobao.org
2、安装react环境 npx create-react-app 项目名称
3、启动项目:cd 项目文件夹
npm start
二、组件和props
1.组件:组件允许你将 UI 拆分为独立可复用的代码片段,并对每个片段进行独立构思。
2.props:调用组件时可以给组件传递参数,props是用来接收传递过来参数的一个属性
3.组件的定义方式:
①函数形式:
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
②class类形式:
class Welcome extends React.Component{
render() {
return (<h1>Hello, {this.props.name}</h1>);
}
}
③ps:1.组件名称必须以大写字母开头
2.调用ReactDom.render(<Welcome />)时,组件是以标签形式调用的,写单标签时必须有结束符号
3.组件调用可以不在ReactDom.render方法中,可以在页面中任何位置
④细节说明:
1.function 和 class 关键字后的名称就是组件名称。
2.return 后就是页面结构,如果页面结构比较复杂,需要使用小括号括起来
3.return 后的页面结构,只能有一个顶级标签,顶级标签不能有兄弟元素
4.组件是页面结构,如果这个组件有自己的css样式,在当前组件中通过import引入
4.props
使用分两步:
1.组件调用时,组件上通过定义属性,传递数据
2.组件内部通过 this.props.属性名称 得到传递的值
eg:调用:<About username="jim" upwd='k123' />
定义:class About extends React.Component{
render(){
return (
<div>
<p>姓名:{this.props.username}</p>
<p>密码:{this.props.upwd}</p>
</div>
)
}
}
3.props是单向传递
4.props是只读属性
5.组件组合:包含关系(插槽)
1. 在调用组件时,在组件标签内部添加其他代码
2. 在组件内部,通过{this.props.children} 能获取到添加代码
调用:
<FancyBorder color="blue">
<h1 className="Dialog-title">
Welcome
</h1>
<p className="Dialog-message">
Thank you for visiting our spacecraft!
</p>
</FancyBorder>
定义:
class FancyBorder extends React.Component{
render(){
return(
<div>
{this.props.children}
</div>
)
}
}
三、state 和 生命周期
1、start
1.state是组件内部的状态,外部不可访问。
2.使用:
1.需要使用es6的class定义组件
2.在class定义组件中添加,state在constructor中初始化
constructor(props) {
super(props);
this.state = {date: new Date()};
}
3.组件内部就可以使用state了
访问:this.state.属性
修改:this.setState({
属性名:属性值
})
setState((state)=>{
})
2、生命周期函数
每一个组件从创建到销毁,过程会有一些自动执行函数,被生命周期函数
componentWillMount : 组件将要被渲染
render: 渲染函数,组件就可以添加页面
componentDidMount : 组件渲染完成,组件会进入运行状态
componentWillReceiveProps: 当props发生改变时,触发这个函数
shouldComponentUpdate: 这个函数的功能是,是否允许组件方式状态改变。如果返回值是true,表示允许改变,这是默认值;如果返回值是false,禁止组件状态改变
componentWillUpdate: 组件将要发生改变
render: 还是渲染函数,这时是更新页面
componentDidUpdate: 组件更新完成
componentWillUnmount:组件将要卸载