Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

240
Views
ReactJs: método de llamada de otro componente que no tiene relación (padre-hijo)

tengo un componente ->

Componente AppLanding que representa otros 2 componentes:

 AppActions AppListings

AppActions y AooListings no tienen conexión entre ellos.

Desde el clic del botón en AppAction , quiero llamar al método en AppListings .

Necesidad de esto -

AppListings contiene Ag-Grid y AppActions contiene acciones de botones. Al hacer clic en el botón en AppActions , quiero llamar al método en AppListings que controla columnapi para Ag-Grid en AppListings

Si tuviera una relación padre-hijo, habría pasado el método a AppListings , pero en este caso no puedo porque no tiene relación.

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Desea que los componentes hermanos se comuniquen. Es posible que desee ver esta respuesta: https://stackoverflow.com/a/36144048/1065780

La idea es usar administradores de estado como redux , o hacer que su componente principal reciba eventos de un hermano y pase accesorios modificados a otro hermano, así:

 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>

about 4 years ago · Juan Pablo Isaza Report

0

Puede usar redux al hacer clic en el evento del botón en la página AppActions y escuchar el estado redux con useeffect en la página AppListings.

 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);
about 4 years ago · Juan Pablo Isaza Report

0

¿Ha considerado el uso de React.Context para crear un proveedor global (o específicamente en el ámbito de sus diseños)? De esta manera podría almacenar sus acciones dentro de un reductor.

ganchos/uso-contexto.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 : Proporcionar estado

 import { Provider } from '../hooks/use-context' const Page = () => ( <Provider> <AppActions /> <AppListings /> </Provider> ) export default Page

components/app-actions.jsx : Actualizar estado

 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 : estado de consumo

 import useContext from '../hooks/use-context' const AppListings = () => { const [state] = useContext() return ( <pre>{JSON.stringify(state, null, 2)</pre> ) } export default AppListings

También puede buscar soluciones de terceros como Redux .

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!