React官网入口
1.hello word
第一步引入react相关库
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<h1>Hello, world!</h1>);
2.jsx语法
设想如下变量声明
const element = <h1>Hello, world!</h1>;
这个标签语法既不是字符串也不是HTML是一个 JavaScript 的语法扩展(jsx)
jsx语法规则: 1.定义虚拟DOM时,不要写引号。
2.标签中混入JS表达式时要用{}。
3.样式的类名指定不要用class,要用className。
4.内联样式,要用style={{key:value}}的形式去写。
5.只有一个根标签
6.标签必须闭合
7.标签首字母
(1).若小写字母开头,则将该标签转为html中同名元素,若html中无该标签对应的同名元素,则报错。
(2).若大写字母开头,react就去渲染对应的组件,若组件没有定义,则报错。
3.react中定义组件
1.函数式组件(推荐)
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
2.类式组件
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
4.组件属性State
函数式组件例子 使用hook函数useState()
import React, { useState } from 'react';
function Example() {
// 声明一个叫 "count" 的 state 变量
const [count, setCount] = useState(0);
return (
<div>
<p>You clicked {count} times</p>
<button onClick={() => setCount(count + 1)}>
Click me
</button>
</div>
);
}
等价于类式组件:
class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
count: 0
};
}
render() {
return (
<div>
<p>You clicked {this.state.count} times</p>
<button onClick={() => this.setState({ count: this.state.count + 1 })}>
Click me
</button>
</div>
);
}
}
1.声明State变量
在函数组件中,我们没有 this,所以我们不能分配或读取 this.state。我们直接在组件中调用 useState Hook
在 class 中,我们通过在构造函数中设置 this.state 为 { count: 0 } 来初始化 count state 为 0或简写(不在构造函数中声明)state={count: 0}
2.读取State
在函数中,我们可以直接用 count: {count}
当我们想在 class 中显示当前的 count,我们读取 this.state.count
3.更新State
在函数中,因为没有this,所以通过count 和 setCount变量去更新
<button onClick={() => setCount(count + 1)}> Click me
</button>
在 class 中,我们需要调用 this.setState() 来更新 count 值
4.组件属性Props
1.函数式组件:
函数式组件的props在创建组件时通过参数传进来
对prop类型进行限制时:
name: PropTypes.string.isRequired,
age: PropTypes.number
}
props设置默认值:
name: 'zhangsan',
age: 18
}
2.类式组件:
类式组件的props在创建组件时挂载在this身上
对prop类型进行限制时:
name: PropTypes.string.isRequired, //限制name必传,且为字符串
sex: PropTypes.string,//限制sex为字符串
age: PropTypes.number,//限制age为数值
speak: PropTypes.func,//限制speak为函数
}
props设置默认值:
sex: '男',//sex默认值为男
age: 18 //age默认值为18
}
5.组件属性refs
1.函数式组件: 使用hook函数useRef() React.forwardRef():
//父组件
import React, { useRef } from 'react'
import UserForm from '../../../components/UserForm';
export default function Users() {
const addForm = useRef(null)
return (
<UserForm ref={addForm} regionList={regionList} roleList={roleList}></UserForm>
)
}
//子组件
import React, { forwardRef } from 'react'
const UserForm = forwardRef((props,ref) => {
return (
<div>
<Form ref={ref}>
</Form>
<div>
)
})
export default UserForm
//在父组件中打印addForm即可得到子组件绑定的DOM元素
2.类式组件:绑定到this身上
三种方式:字符串形式的refs、回调函数形式的refs(推荐)、createRef()
6.React的事件处理
1.通过onXxx属性指定事件处理函数(注意大小写)
a.React使用的是自定义(合成)事件, 而不是使用的原生DOM事件 —为了更好的兼容性 b.React中的事件是通过事件委托方式处理的(委托给组件最外层的元素) —为了的高效
2.通过event.target得到发生事件的DOM元素对象 —不要过度使用ref
7.非受控组件和受控组件
非受控组件和受控组件的区别:非受控组件在在需要用的时候获取节点从而获取值,受控组件是将值直接绑定到state里面,在需要用时直接从state中读取
8.条件渲染
根据用户是否登录(isLoggedIn)来决定显示上面的哪一个组件
function Greeting(props) {
const isLoggedIn = props.isLoggedIn;
if (isLoggedIn) { return <UserGreeting />; } return <GuestGreeting />;}
const root = ReactDOM.createRoot(document.getElementById('root'));
// Try changing to isLoggedIn={true}:
root.render(<Greeting isLoggedIn={false} />);
9.Hooks
1.useState() 使用方法第四条
2.useEffect()
useEffect(callback,optional)
callback: 回调函数-----------在组件首次渲染之后执行
optional: 可选参数([])-----是一个数组,当数组中的元素发生变化时执行callback,只需要执行一次是为空数组即可
Effect Hook 可以让你在函数组件中执行副作用操作,
提示:
如果你熟悉 React class 的生命周期函数,你可以把 useEffect Hook 看做 componentDidMount,componentDidUpdate 和 componentWillUnmount 这三个函数的组合。
你可能认为需要单独的 effect 来执行清除操作。但由于添加和删除订阅的代码的紧密性,所以 useEffect 的设计是在同一个地方执行。如果你的 effect 返回一个函数,React 将会在执行清除操作时调用它:
useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}
ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
// Specify how to clean up after this effect:
return function cleanup() {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
});
3.useConText()
const themes = {
light: {
foreground: "#000000",
background: "#eeeeee"
},
dark: {
foreground: "#ffffff",
background: "#222222"
}
};
const ThemeContext = React.createContext(themes.light);
function App() {
return (
<ThemeContext.Provider value={themes.dark}>
<Toolbar />
</ThemeContext.Provider>
);
}
function Toolbar(props) {
return (
<div>
<ThemedButton />
</div>
);
}
function ThemedButton() {
const theme = useContext(ThemeContext); return ( <button style={{ background: theme.background, color: theme.foreground }}> I am styled by theme context! </button> );
}