安装
cnpm i create-react-app -g
create-react-app xxoo
jsx相关
jsx的元素的属性有两个特例,class为className,for为htmlFor
父传子
父
value={i}
子
{this.props.value}
子传父
子
onClick={() => {
this.props.event();
}}
父
<Square
value={this.state.squares}
event={() => {
this.handleClick(i);
}}
/>
函数组件
const Square=(props)=>{
return (
<button
className="square"
onClick={props.event}>
{props.value}
</button>
)
}
React.Component 类组件react组件的构造函数用于初始化,使用时加上super
class Square extends React.Component {
constructor(props) {
super(props);
this.state = {
squares: Array(9).fill(null),
};
}
render() {}
}
React.Context 全局传 值//创建context对象
import React from 'react'
//context用法
const ThemeContext=React.createContext(默认值)
export default Context;
上级元素:
import Context...
<Context.Provider value=></Context.Provider>
下级元素:
class中contextType 属性 取值
static contextType = MyContext;
render中使用
<Context.Consumer>{(实参) =>
{return(
<div value=实参></div>
)
}
</Context.Consumer>
组件的生命周期
监听更新
componentDidUpdate(prevProps,pervState){前一次的prop和state }
- setState() 在组件中调用 setState 时,React 都会自动更新其子组件。
- 在 map() 方法中的元素需要设置 key 属性。
- 在class中自定义方法需要绑定this。在构造函数中绑定(this.like=this.like.bind(this))或者用箭头函数(let like=()=>{})
- 非受控组件 ,使用ref返回值 ref={(text)=>{this.text=text}} 获得DOM的属性:this.text.value
在组件中使用style
npm i styled-components
如果在typescript中:
npm i -s @types/styled-components
import styled from 'styled-components'const CompositionStyle = styled.div` .FancyBorder{ border: 1px solid #111111; width:50px }`
Refs
创建fefs
class MyComponent extends React.Component {
constructor(props) {
super(props);
this.myRef = React.createRef(); }
render() {
return <div ref={this.myRef} />; }
}
获取
const node = this.myRef.current;
你不能在函数组件上使用 ref 属性
Hook:
只能在函数最外层调用 Hook。
只能在 React 的函数组件中调用 Hook。
自定义 Hook 必须以 “use” 开头
useState 设置state
定义
const [age, setAge] = useState(42);
const [fruit, setFruit] = useState('banana');
设置
setCount(count + 1)
useEffect类似于componentDidMount、componentDidUpdate 和 componentWillUnmount合一
例子:
useEffect(() => { // 使用浏览器的 API 更新页面标题 document.title = `You clicked ${count} times`; });