【问题标题】:How can I pass a value from a function to any component in React?我如何将一个值从函数传递给 React 中的任何组件?
【发布时间】:2022-12-12 14:52:22
【问题描述】:

我想传递一个我在这样的函数中接收到的值:

const ViewDetails = item => () => {
   console.log(item);
   toggleModal();
}

我想将项目传递给模态组件喜欢打开,关闭在 Main 函数中调用:

return (
   <Layout title="Dashboard" className="container-fluid">
      {<Modal open={modalStatus} onClose={() => setModalStatus(false)} />}
      <div className="row">
         <div className="col-sm-3">
            <UserLinks />
         </div>
         <div className="col-sm-9">
             <UserInfo />
             {orders ? <PurchaseHistory /> : ""}
         </div>
      </div>
   </Layout>
)

我期待有这样的事情: {&lt;Modal open={modalStatus} onClose={() =&gt; setModalStatus(false)} ***item={item}***/&gt;} 这样我就可以在 Modal 组件中使用 item 内的值。

【问题讨论】:

  • 请添加使用的 ViewDetails() 部分。
  • 我无法理解这个问题。你能进一步解释一下吗?
  • 所以,我收到了物品来自 viewDetails 函数中的另一个组件。在我单击 viewDetails 后,它会更改状态值,使模式出现。每当触发 viewDetails 函数时,我想将 item 变量传递给 Modal 组件,以便我可以在模式中使用它。
  • 我的意思是,需要查看调用它的函数,代码不完整

标签: reactjs react-functional-component


【解决方案1】:

我想通过提供一个非常简单的示例以及有关 Context hook 的 React 文档,向@GODWIN GODWIN 评论添加更多关于上下文 API 的信息

通常在实践中人们倾向于将提供者包装在 App.js 中,为了简单起见,我将包装在 index.js 文件中。

源代码/index.jsx

import React from 'react';
import ReactDOM from 'react-dom/client';

import App from './App'
import { ModalProvider } from './context/ModalContext'

ReactDOM.createRoot( 
  document.querySelector('#root')
).render(
  /**
   * @dev Note everything inside ModalPrivder has access
   * to the values provided, such as open, setOpen
   */
  <ModalProvider>
    <App />
  </ModalProvider>
)

src/上下文/ModalContext.jsx

import React, {useState, createContext, useContext } from 'react'

/**
 * @dev inside your createContext object you can pass in
 * default values that will be passed in value at provider
 */
export const ModalContext = createContext({
 open: false
})

/**
 * @dev your provider will enable you to access value all your
 * children components. NOTE it will not be able to access your
 * parent components.
 */
export function ModalProvider(props) {
  const [open, setOpen] = useState(false)

  return (
    <ModalContext.Provider value={{ open, setOpen }}>
      {props.children}
    </ModalContext.Provider>
  )
}

源代码/组件/Modal.jsx

import { useContext } from 'react'

function Modal(props) {
  const { open, setOpen } = useContext(ModalContext)

  return (
    <>
      { open ? 
        (<div>
          <p>test</p>
          <>{props.children}</>
          <button onClick={() => setOpen(false)}>Close Close</button>
        </div>) : 
        (<button onClick={() => setOpen(true)}>Open Modal</button>)
      }
    </>
  )
}

export default Modal

源代码/App.jsx

function App(props) {
  return (
    <div className='App'>
      <h1>Hello React.</h1>
      <h2>Start editing to see some magic happen!</h2>
      <Modal>
        <p> You see content here</p>
      </Modal>
    </div>
  );
}

export default App

我希望这能为您提供有关如何使用 React 上下文挂钩的良好指导,请注意这是一个非常基本的源代码,以了解 props.children 和 context 挂钩的工作原理。

【讨论】:

    【解决方案2】:

    你可以试试这个:

    import React from "react";
    
    function Eexample() {
      const ViewDetails = (item) => () => {
          console.log(item);
          toggleModal();
          return (
              <Modal item={item} /> //This is passing item into the Modal component
          )
      };
      return <div>
        {ViewDetails}  {/*This returns the function viewDetails*/}
      </div>;
    }
    
    export default Eexample;
    

    对于您的模态组件:

    function Modal({ item }) {  // with this distructuring, you can use the item inside the Modal component
            return (
                <Layout title="Dashboard" className="container-fluid">
                   {<Modal open={modalStatus} onClose={() => setModalStatus(false)} />}
                   <div className="row">
                      <div className="col-sm-3">
                         <UserLinks />
                      </div>
                      <div className="col-sm-9">
                          <UserInfo />
                          {orders ? <PurchaseHistory /> : ""}
                      </div>
                   </div>
                </Layout>
             )
          }
    

    或者考虑使用上下文 API,它使您能够将项目分派到 reducer.js 文件并使用 StateProvider.js 文件将其拉入模态组件。

    【讨论】:

      【解决方案3】:

      您必须为此项目获取状态。当从这个函数内部触发 viewDetails 函数时,你可以用这个项目设置这个状态,之后可以将这个状态作为道具传递给任何组件

      【讨论】:

      • 请提供源代码的解决方案,请提供您是如何想出解决方案的,这将对以后遇到类似问题的会员有所帮助,欢迎来到StackOverflow!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-26
      • 1970-01-01
      • 2021-10-29
      • 2021-09-30
      • 1970-01-01
      • 2018-05-07
      相关资源
      最近更新 更多