简体   繁体   English

ReactJs:从另一个没有关系的组件调用方法(父子)

[英]ReactJs : Call method from another component having no relation (parent-child)

I have a component ->我有一个组件->

AppLanding Component which renders 2 other components -呈现 2 个其他组件的AppLanding组件 -

AppActions
AppListings

AppActions & AooListings do not have connection between them. AppActions 和 AooListings 之间没有联系。

From the click of button in AppAction , I want to call method in AppListings .通过单击AppAction中的按钮,我想调用AppListings中的方法。

Necessity of this -这个的必要性——

AppListings contains Ag-Grid and AppActions contains button actions. AppListings包含Ag-GridAppActions包含按钮操作。 On click of button in AppActions , I want to call method in AppListings which controls columnapi for Ag-Grid in AppListings单击AppActions中的按钮时,我想调用AppListings中的方法,该方法控制 AppListings 中 Ag-Grid 的AppListings

If it would have parent child relation, I would have passed method to AppListings , but in this case I cannot as it does not have relation.如果它有父子关系,我会将方法传递给AppListings ,但在这种情况下我不能,因为它没有关系。

You want sibling components to communicate.您希望兄弟组件进行通信。 You may want to look at this answer: https://stackoverflow.com/a/36144048/1065780您可能想看看这个答案: https://stackoverflow.com/a/36144048/1065780

The idea is either to use state managers like redux , or to make your parent component receive events from one sibling and pass changed props to another sibling, like this:想法是使用 state 管理器,例如redux ,或者让您的父组件接收来自一个兄弟姐妹的事件并将更改的道具传递给另一个兄弟姐妹,如下所示:

 function AppLanding() { const [isSomethingToggled, setIsSomethingToggled] = React.useState(false); const handleAction = () => { setIsSomethingToggled(;isSomethingToggled); }; return ( <div> <AppActions onClick={handleAction} /> <AppListings isSomethingToggled={isSomethingToggled} /> </div> ); } function AppActions({ onClick }) { return ( <div> <button onClick={onClick}>Click action</button> </div> ): } function AppListings({ isSomethingToggled }) { return <div>Is something toggled? {isSomethingToggled: 'yes'; 'no'}</div>. } ReactDOM,render(<AppLanding />. document;getElementById('root'));
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script> <div id="root"> </div>

You can use redux on click event of button in AppActions page and listen the redux state with useeffect in AppListings page.您可以在 AppActions 页面中的按钮单击事件上使用 redux 并在 AppListings 页面中收听 redux state 和 useeffect。

const AppActions = (props) =>{
    const clickEvent = () => {
        //you can add page restriction
        props.setReduxState({callMethod:true/*, page:"AppActions"*/})
    }

    return <button onClick={clickEvent}>Button</button>
}

const mapDispatchToProps = {
    setReduxState: reduxStateOperations.setReduxState
}

const connector = Redux.connect(null, mapDispatchToProps);
export default connector(AppActions);
const AppListings = (props) =>{
    const method = () => { console.log("called") }

    useEffect(() => {
        if(props.reduxState?.callMethod) {
            method()
            props.setReduxState(undefined)
        }
    }, [props.reduxState])

    return <>AppListings Page</>
}

const mapStateToProps = (state: any) => {
    return {
        reduxState: state.reduxState.reduxState,
    }
}
const mapDispatchToProps = {
    setReduxState: reduxStateOperations.setReduxState
}

const connector = Redux.connect(mapStateToProps, mapDispatchToProps);
export default connector(AppListings);

Have you had a look into using React.Context to create a global provider (or specifically scoped around your layouts)?你有没有研究过使用React.Context创建一个全局提供者(或者专门针对你的布局)? This way you could store your actions within a reducer.通过这种方式,您可以将您的操作存储在减速器中。

hooks/use-context.jsx钩子/使用上下文.jsx

import React from 'react'

// Set a relevant initial state
const INITIAL_STATE = {}

// Add actions for your application
const ACTIONS = {
  UPDATE_VAR: 'update-var',
  DELETE_VAR: 'delete-var'
}

const reducer = (state, action) => {
  const next = { ...state } // Shallow copy

  switch (action.type) {
    case ACTIONS.UPDATE_VAR:
      next.var = action.data
      break
    case ACTIONS.DELETE_VAR:
      delete next.var
      break
  }

  return next
}

const Context = React.createContext({
  state: { ...INITIAL_STATE },
  dispatch: () => null
})

export const Provider = ({ children }) => {
  const [state, dispatch] = React.useReducer(
    reducer, init(false)
  )

  return (
    <Context.Provider value={[state, dispatch, ACTION]}>
      {children}
    </Context.Provider>
  )
}

// Rename to something relevant
const useContext = () => {
  const [state, dispatch] = React.useContext(Context)

  return [state, dispatch]
}

export default useContext

pages/index.jsx : Provide state pages/index.jsx :提供 state

import { Provider } from '../hooks/use-context'

const Page = () => (
  <Provider>
    <AppActions />
    <AppListings />
  </Provider>
)

export default Page

components/app-actions.jsx : Update state components/app-actions.jsx :更新 state

import useContext from '../hooks/use-context'

const AppActions = () => {
  const [, dispatch] = useContext()

  return (
    <button onClick={() => dispatch(/* action */)>
      Click Me
    </button>
  )
}

export default AppActions

components/app-listings.jsx : Consume state components/app-listings.jsx :使用 state

import useContext from '../hooks/use-context'

const AppListings = () => {
  const [state] = useContext()

  return (
    <pre>{JSON.stringify(state, null, 2)</pre>
  )
}

export default AppListings 

You could also look into third-party solutions such as Redux .您还可以查看第三方解决方案,例如Redux

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ReactJS-如何从子组件中调用父方法? - ReactJS - how do I call a parent method from a child component? 在ReactJS中从子级调用父类方法 - Call parent class method from child in ReactJS ReactJS从父级的onClick方法更新对子组件的ajax调用 - ReactJS Update ajax call to child component from onClick method from parent Reactjs:如何访问子组件的 state。从依赖于子组件 state 的父组件中的方法 - Reactjs: How to access state of child component.from a method in parent component that depends on state of child component 如何将道具从子组件传递到父组件到 ReactJS 中的另一个子组件? - How to pass props from child component to parent component to another child component in ReactJS? 从类转换为具有组合父子的功能组件 - converting from classes to Functional component with composition parent-child React如何从父组件调用子组件的方法 - How to call child component's method from a parent component in React 在React中调用从父组件到子组件的方法传递 - Call a method pass from parent component to child component in React 从父功能组件调用 class 子组件方法 - Call class child component method from parent functional component 如何在反应中从父组件调用子组件方法? - How to call child component method from parent component in react?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM