React系列学习-父子组件传值

103 阅读1分钟
  1. props
  • 适用于父子组件通信
//Father.ts
const Father = () => <div>Father<Children name={'annie'} /> </div>

//Children.ts
const Children = (name) => <div>Children: {name}</div>
  1. useContext
  • 适用于祖先/后代组件
  • 不适用于大量使用,Context.value发生改变,涉及所有组件要更新
const FatherContext = useContext(null)

<FatherContext.Provider value={{name: 'annie'}}>
    <Children />
</FatherContext.Provider>

//Children.ts
const {name} = useContext(FatherContext);
  1. redux
  • 适用于远亲组件,组件的层级关系不确定的情况
// reducer.ts
const updateState = (state, action):  => {
  switch (action.type) {
    case 'TODO':
      return { ...state, todo: 'right now' };
  }
};

// action.ts
function setTodo(param): TodoAction {
  return {
    type: 'TODO',
    payload: { todo: param }
  };
}
  1. recoil atom, selector
// store.ts
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`;
    }
})


// app.ts 来自B站2小时搞定Recoil视频
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>
    )
}