React TypeScript中如何实现状态包装组件向子组件传递Props?
实现带状态传递的React包装组件方案
方式一:将 Children 作为函数传递(最贴近你的需求)
直接调整代码结构,让包装组件把内部状态通过函数参数传递给子组件:
const MyChild = (props:{state:boolean}) => { return <Text>{`the state is ${props.state}`}</Text> } // 将children类型改为接收状态参数的函数 const StateWrapper = ({children}:{children: (state: boolean) => React.ReactNode}) => { const hookState: boolean|null = useHookState() // 状态未就绪时渲染Loading if (hookState === null) return <Loading /> // 调用children函数并传入状态 return children(hookState) } const App = () => { return ( <StateWrapper> {/* 以函数形式接收状态,再传递给MyChild */} {(state) => <MyChild state={state} />} </StateWrapper> ) }
这种写法完全匹配你想要的抽象逻辑,包装组件负责管理状态和加载状态,子组件只需要接收状态并渲染即可。
方式二:Render Props 模式
和上面的逻辑本质一致,只是把渲染逻辑放到单独的render属性中,写法更明确:
const MyChild = (props:{state:boolean}) => { return <Text>{`the state is ${props.state}`}</Text> } const StateWrapper = ({render}:{render: (state: boolean) => React.ReactNode}) => { const hookState: boolean|null = useHookState() if (hookState === null) return <Loading /> return render(hookState) } const App = () => { return ( <StateWrapper render={(state) => <MyChild state={state} />} /> ) }
方式三:React Context(适合多组件共享状态)
如果应用中有多个层级的组件都需要使用这个状态,用Context可以避免逐层传递props的麻烦:
import React from 'react' // 创建状态Context const StateContext = React.createContext<boolean | null>(null) const StateWrapper = ({children}:{children: React.ReactNode}) => { const hookState: boolean|null = useHookState() if (hookState === null) return <Loading /> // 用Provider把状态注入到子组件树中 return ( <StateContext.Provider value={hookState}> {children} </StateContext.Provider> ) } // 子组件直接通过useContext获取状态 const MyChild = () => { const state = React.useContext(StateContext) return <Text>{`the state is ${state}`}</Text> } const App = () => { return ( <StateWrapper> <MyChild /> {/* 其他需要状态的子组件也可以直接在这里使用 */} </StateWrapper> ) }
内容的提问来源于stack exchange,提问作者branperr
相关产品推荐
相关产品推荐

