[英]How to change sibling component on event from another component in React JS
[英]how to load an image in another component by click event on sibling component in react
我是新來的反應,想有一個基本的反應應用程序。 我有兩個兄弟組件。 在一個組件(ImagePreview)中,我有一個圖像列表,我顯示為縮略圖列表。 我有另一個組件(ImageReal),我想在其中顯示全尺寸圖像。
我想更新 ImageReal 的 state,這樣當單擊 ImagePreview 組件中的圖像時,它會更新 imageReal 中的 state,並且該圖像將顯示在 ImageReal 中。 我看過很多例子,但我無法理解可能是 b/c 我對這些東西不熟悉。
import React from 'react';
import './styles/app.css';
import ImagePreview from './components/ImagePreview'
const ImageList = [{imagePreview: "/image/image1.jpg"},{imagePreview: "/image/image2.jpg"},{imagePreview: "/image/image3.jpg"}];
function App() {
return (
<div className="flex mb-4">
<div className="w-1/4 bg-gray-400 h-screen mx-2 my-1">
{ ImageList.map(image => (
<ImagePreview key={image.id} image={image} ></ImagePreview>
))}
</div>
<div className="w-3/4 bg-gray-500 h-screen mx-2 my-1">
</div>
</div>
);
}
export default App;
圖像預覽組件
import React from 'react'
const ImagePreview = ({ image }) => {
let helloWorld = (e) => {
console.log('Hello world :', e.target);
}
return (
<div className="py-5 px-10">
<img src={image.previewURL} className="w-full" onClick={helloWorld}/>
</div>
);
}
export default ImagePreview
ImageReal 組件
import React from 'react'
const ImageReal = ({ image }) => {
return (
<div className="py-5 px-10">
<img src={image.previewURL} className="w-full" />
</div>
);
}
export default ImageReal
如果您希望兩個組件相互交互,那么在一個共同的父祖先組件中管理 state 可能是一個好主意。
有關更多信息,請參閱此鏈接:https://reactjs.org/docs/lifting-state-up.html#lifting-state-up
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.