- props
const Father = () => <div>Father<Children name={'annie'} /> </div>
const Children = (name) => <div>Children: {name}</div>
- useContext
- 适用于祖先/后代组件
- 不适用于大量使用,Context.value发生改变,涉及所有组件要更新
const FatherContext = useContext(null)
<FatherContext.Provider value={{name: 'annie'}}>
<Children />
</FatherContext.Provider>
const {name} = useContext(FatherContext);
- redux
const updateState = (state, action): => {
switch (action.type) {
case 'TODO':
return { ...state, todo: 'right now' };
}
};
function setTodo(param): TodoAction {
return {
type: 'TODO',
payload: { todo: param }
};
}
- recoil
atom, selector
import { atom, selector } from 'recoil';
export const fontSizeAtom = atom({
key: 'fontSizeAtom',
default: 20
})
export const fontSizeState = selector({
key: 'fontSizeState',
get: ({get}) => {
const fontSizeNum = get(fontSizeAtom);
return `${fontSizeNum}px`;
}
})
import {useRecoilState, useRecoilValue} from 'recoil';
import {OtherState} from '../../store';
function SelectorFontSize() {
const [fontNum, setFontNum] = useRecoilState(OtherState.fontSizeAtom);
const fontSizeState = useRecoilValue(OtherState.fontSizeState);
const marks = {
12: '12',
14: '14',
16: '16',
18: '18',
20: '20',
22: '22',
24: '24',
26: '26',
28: '28',
30: '30',
32: '32',
34: '34',
};
return (
<div>
<Slider
marks={ marks }
min={12}
max={34}
step={2}
defaultValue={ fontNum }
onChange={ (e: any) => setFontNum(e) }
/>
<span style={{ fontSize: fontSizeState }}>
验证文字大小 - { fontNum }
</span>
</div>
)
}