[英]Subscribe to action in one React component published from another
Imagine the following situation: we've developed two smart components and released two npm packages.想象一下以下情况:我们开发了两个智能组件并发布了两个 npm 封装。 After that we imported components to third React application which developed by another team.
之后,我们将组件导入另一个团队开发的第三个 React 应用程序。
package.json package.json
"dependencies": {
"component-ui1": "0.1.1",
"component-ui2": "0.1.0"
}
App.jsx应用程序.jsx
import React, { useEffect } from 'react';
import ComponentUI1 from 'component-ui1';
import ComponentUI2 from 'component-ui2';
export const App = () => {
useEffect(() => {
// Some asynchronous actions
}, []);
return (
<>
<ComponentUI1 someProp={true} />
<ComponentUI2 someProp={false} />
</>
);
};
How can I generate an event in ComponentUI1
through DOM so that it triggers an action in ComponentUI2
, for example, updating some list?如何通过 DOM 在
ComponentUI1
中生成事件,以便触发ComponentUI2
中的操作,例如更新某些列表? Preferably without modifying logic of source components.最好不修改源组件的逻辑。
The right way to do it is正确的做法是
Make the parent container make the update使父容器进行更新
import React, { useEffect } from 'react'; import ComponentUI1 from 'component-ui1'; import ComponentUI2 from 'component-ui2'; export const App = () => { useEffect(() => { // Some asynchronous actions }, []); const [listAbc, setListAbc] = useState(0); const eventAbc = () = { //... update listAbc // setListAbc() } return ( <> <ComponentUI1 someProp={true} someEvent={eventAbc} /> <ComponentUI2 someProp={false} someList={listAbc} /> </> );
}; };
import React, { useState, useEffect } from 'react';
import ComponentUI1 from 'component-ui1';
import ComponentUI2 from 'component-ui2';
export const App = () => {
const [state, setState] = useState({ComponentUI1List: [], ComponentUI2List: []});
useEffect(() => {
// Some asynchronous actions
}, []);
return (
<>
<ComponentUI1 state={state} changeState={(data) => setState(data)} />
<ComponentUI2 state={state} changeState={(data) => setState(data)} />
</>
);
};
now in your ComponentUI1 or 2 you can change ComponentUI1List
or ComponentUI2List
like so:现在在您的 ComponentUI1 或 2 中,您可以像这样更改
ComponentUI1List
或ComponentUI2List
:
// ComponentUI1.jsx
import React from 'react';
export const App = (props) =>
(
<>
<div className="container">
<button onClick=(props.changeState({...props.state, ComponentUI2List: [{id: 1, title: "New Generated Data"}]}))
</div>
</>
);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.