React学习笔记
JSX能够简单理解为标签和js的结合
例如:
const element=<h1>hello,world</h1>
具体的例子如下:
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
function formatName(user){
return user.firstName+''+user.lastName
}
const user={
firstName:'小',
lastName:'洋洋'
}
function getGreeting(user){
if(user){
return <h1>hello,{formatName(user)}!</h1>
}
return <h1>hello,Stanger</h1>
}
// ========================================
ReactDOM.render(
//<Game />,
getGreeting(user),
document.getElementById('root')
);
JSX就是一种值的形式
可以使用属性指定(=)字符串字面量,如果是在其中加入变量的话就需要加上{}
如果是要让其标签看起来很有格式的话可以这样加上小括号
const element = (
<div>
<h1>Hello!</h1>
<h2>Good to see you here.</h2>
</div>
);
JSX表示对象
JSX会被转译成一个名为React.createElement()函数调用
const element = (
<h1 className="greeting">
Hello, world!
</h1>
);
const element = React.createElement(
'h1',
{className: 'greeting'},
'Hello, world!'
);
React.createElement()
会预先执行一些检查,以帮助你编写无错代码,但实际上它创建了一个这样的对象:
const element={
type:'h1',
props:{
className:'greeting',
children:'hello,world'
}
}
不改变参数的函数被称为纯函数,改变参数的函数为不纯,react的严禁改变参数值的,它自己会进行检测并报错
State&生命周期
function Clock extends React.Component{
constructor(props){
super(props)
this.state={date:new Date()}
}
componentDidMount(){//mount为挂载
this.timerID=setInterval(()=>this.tick() ,1000)
}
componentWillUnmount(){//unmount为卸载 理解为清除
clearInterval(this.timerID)
}
render(){
return (
<div>
<h1>hello,world!</h1>
<h2>It is {this.state.date.toLocaleString()}.</h2>
</div>
)
}
}
function tick(){
ReactDOM.render(
<Clock/>,
document.getElementById('root')
)
}
正确地使用state
不要直接修改state而是使用setState()进行修改
由于this.props和this.state可能异步更新,所以不能够利用它们进行相关更新
事件处理
react事件的命名采用小驼峰式,而不是纯小写
使用JSX语法时你需要传入一个函数作为事件处理函数,而不是一个字符串
<button onclick="activateLasers()">
Activate Lasers
</button>
在React中略微不同
<button onClick={activateLasers}>
Activate Lasers
</button>
在react中另一个不同点是你不能通过返回false的方式阻止默认行为,必须显性的使用event.preventDefault()来进行阻止,
class Toggle extends React.Component {
constructor(props) {
super(props);
this.state = {isToggleOn: true};
// 为了在回调中使用 `this`,这个绑定是必不可少的
this.handleClick = this.handleClick.bind(this);//javascript默认不会绑定this要手动进行绑定
}
handleClick() {
this.setState(prevState => ({
isToggleOn: !prevState.isToggleOn
}));
}
render() {
return (
<button onClick={this.handleClick}>
{this.state.isToggleOn ? 'ON' : 'OFF'}
</button>
);
}
}
ReactDOM.render(
<Toggle />,
document.getElementById('root')
);
条件渲染
组件可以是方法也可以是类(但是类需要构造函数,super(props),方法就需要传入参数这个参数就是prop)
阻止组件渲染
在极少数情况下,你可能希望能隐藏组件,即使它已经被其他组件渲染。若要完成此操作,你可以让 render
方法直接返回 null
,而不进行任何渲染。
表单可以使用value来标识标签从而来构建组件 推荐技术有 Formik ,
状态提升
通常多个组件需要反映相同的变化数据,建议将共享状态提升到最近的共同组件中去
在自定义的模板中再传入内置的标签的话如果是一次性的插入不区分的话可以使用props.childern
如果是要进行区分的话可以将特定插入的模板当是标签属性
react用于移动端的有react native
Angular = React/Vue + 路由库(react-router/vue-router) + 状态管理(Redux/Flux/Mobx/Vuex) + 脚手架/构建(create-react-app/Vue CLI/Webpack) + ...