Open lilunze opened 1 year ago
create-react-app (https://create-react-app.dev/)
组件传值
// child.tsx
interface props {
str?: String,
getMsg: Function
}
const Child: React.FC<props> = (props) => {
const { str, getMsg } = props
return (
<>
{ str }
<button onClick={ getMsg('这是子组件传递给父组件的值')}>发送</button>
</>
)
}
// parent.tsx
const Parent: React.FC = () => {
const str = '这是父组件传递给子组件的值'
const getMsg = (data: string) => {
console.log(data)
}
return(
<>
<Child str={ str } getMsg={ getMsg } />
</>
)
}
// Child.tsx
import BusService from '@/utils/eventBus'
const Child:React.FC = () => {
const handleClick = () => {
BusService.emit('send', '这是传递给兄弟组件的值')
}
return (
<>
<button onClick={ handleClick }>发送</button>
</>
)
}
// Brother.tsx
import BusService from '@/utils/eventBus'
const Brother: React.FC = () => {
BusService.on('send', (data: String) => {
console.log(data)
})
}
生命周期
componentDidMount()
|| useEffect(() => {}, [])
componentWillUnmount()
|| useEffect(() => { return () => { /* will unmount */}}, [])
componentDidUpdate()
||
const mounted = useRef();
useEffect(() => {
if (!mounted.current) {
mounted.current = true;
} else {
/* didUpdate */
}
});
ref
// Child.tsx
import React, { useImperativeHandle } from 'react';
const Child:React = React.forwardRef((props, ref) => {
const methods = () => {
console.log('这是子组件的方法')
}
useImperativeHandle(ref, () => {
// 将组件中的方法或属性转发出去
return {
methods
}
})
return (
<></>
)
})
// Parent.tsx
import { useRef } from 'react';
import Child from './Child';
const Parent: React.FC = () => {
const childRef = useRef()
const handleClick = () => {
// 调用子组件中的方法
childRef.current.methods()
}
return (
<>
<button onClick="handleClick">点击</button>
<Child ref={ childRef } />
</>
)
}
Context
// parent.tsx
import { ThemeContext } from "@/utils/context"
const Parent: React.FC = () => {
const [ contextValue , setContextValue ] = React.useState({ color:'green' })
return (
<ThemeContext.Provider value={ contextValue }>
<Child></Child>
<button onClick={ () => { setContextValue({color: 'red'}) } }>红色</button>
<button onClick={ () => { setContextValue({color: 'green'}) } }>绿色</button>
</ThemeContext.Provider>
)
}
// child.tsx
import { useContext } from 'react'
import { ThemeContext } from "@/utils/context"
const Child: React.FC = () => {
const { color } = useContext(ThemeContext)
return (
<div style={{ color }}>Hello React Context</div>
)
}
// utils/context
import React from 'react';
const ThemeContext = React.createContext({ color: 'black' });
export { ThemeContext }
umi (https://umijs.org/)