沙盒:https://codesandbox.io/s/react-context-consumer-passing-method-to-nested-child-forked-u0bi8const initData = {数据:{ a:来自上下文的文本",b:2";},方法:() =>{console.log("方法调用.");}};const SomeContext = React.createContext();导出默认函数 App() {返回 (<SomeContext.Provider value={initData}><内容/></SomeContext.Provider>);}功能内容(){返回 (<div><SomeButton/>);}函数 SomeButton() {返回 (<SomeContext.Consumer>{({数据,方法}) =><button onClick={method}>{data.a}</button>}</SomeContext.Consumer>);}使用上下文挂钩useContext 钩子也可用,并且可能提供更熟悉的模式.上下文的消费者仍然需要是提供者的后代,但它是通过钩子而不是消费者组件来访问的.沙盒:https://codesandbox.io/s/react-context-passing-method-to-nested-child-1fcnoconst initData = {数据:{ a:来自上下文的文本",b:2";},方法:() =>{console.log("方法调用.");}};const SomeContext = React.createContext();导出默认函数 App() {返回 (<SomeContext.Provider value={initData}><工具栏/></SomeContext.Provider>);}功能工具栏(道具){返回 (<div><SomeButton/>);}函数 SomeButton() {const { 数据,方法 } = React.useContext(SomeContext);return {data.a};}I have a component that renders:<View> <SomeContext.Provider value={state}> {props.children} </SomeContext.Provider></View>I don't understand how to create a method accessible in the following way:<View> <SomeContext.Provider> {(method) => <Button title={"Magic"} onPress={() => { method() }} ></Button> } </SomeContext.Provider></View> 解决方案 Consumer ComponentYou need to consume a context through a Context.Consumer that is a direct descendent of the the relevant Provider. The docs have decent examples, though they mix class-based and functional components. Updating Context from a Nested ComponentSandbox: https://codesandbox.io/s/react-context-consumer-passing-method-to-nested-child-forked-u0bi8const initData = { data: { a: "Text from Context", b: "2" }, method: () => { console.log("Method called."); }};const SomeContext = React.createContext();export default function App() { return ( <SomeContext.Provider value={initData}> <Content /> </SomeContext.Provider> );}function Content() { return ( <div> <SomeButton /> </div> );}function SomeButton() { return ( <SomeContext.Consumer> {({ data, method }) => <button onClick={method}>{data.a}</button>} </SomeContext.Consumer> );}useContext HookThe useContext hook is also available, and possibly provides a more familiar pattern. The Consumer of the context still needs to be a descendant of the Provider, but it is accessed via an hook rather than through a Consumer component.Sandbox: https://codesandbox.io/s/react-context-passing-method-to-nested-child-1fcnoconst initData = { data: { a: "Text from Context", b: "2" }, method: () => { console.log("Method called."); }};const SomeContext = React.createContext();export default function App() { return ( <SomeContext.Provider value={initData}> <Toolbar /> </SomeContext.Provider> );}function Toolbar(props) { return ( <div> <SomeButton /> </div> );}function SomeButton() { const { data, method } = React.useContext(SomeContext); return <button onClick={method}>{data.a}</button>;} 这篇关于如何在子组件可以访问的上下文中创建方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-15 23:05