useRef
import React, {forwardRef, useId, useImperativeHandle, useRef,useState} from "react";
export default function(){
const uniqId=useId();
const video=useRef();
const childRef=useRef();
function getInfo() {
alert(`${childRef.current.Title}`);
alert(`${childRef.current.Price}`);
alert(`${childRef.current.Description}`);
}
function setInfo() {
childRef.current.Price=145;
}
return <>
<h1>{uniqId}</h1>
<button onClick={()=>{video.current.play();}}>Play</button>
<button onClick={()=>{video.current.pause();}}>Stop</button>
<video ref={video}>
<source src={"https://www.w3schools.com/html/mov_bbb.mp4"}/>
</video>
<button >Get Product Information</button>
<Product img={"https://fastly.picsum.photos/id/401/536/354.jpg?hmac=klYND-Hud0ew2KcwY00pvGKab0He7yTlDBfKXOvIH3g"}
price={123}
title={"Computer"}
description={"this is my Description"} ref={childRef} />
<button onClick={getInfo}>Get Product Info</button>
<button onClick={setInfo}>SetInfo</button>
</>
}
const Product=forwardRef((props,ref)=>{
const [image,setImage]=useState(props.img);
useImperativeHandle(ref,()=>({
Image:image,
Title:props.title,
Description:props.description,
Price:props.price,
}));
return <>
<h1>Computer</h1>
<img src={image} width={200}/>
<h1>{props.title}</h1>
<p>{props.description}</p>
<label>{props.price}</label>
</>
});
Comments
Post a Comment