<div>1</div>
I would like to obtain 1 of using reactjs.
If it's a pure javascript, it's easy to get it from getelementbyid, but if it's react, which process should I follow to get it?
I would like to use ref in the function component.
If you follow the documentation, you can write:
const Component=()=>{
const ref = React.useRef(null);
// Click to retrieve example
constonClick=()=>{
if(!ref){
return;
}
console.log(ref.current.innerText); // Get here
};
return(
<div>
<div ref={ref}>1</div>
<button type="button" onClick={onClick}>Debug</button>
</div>
);
};
ReactDOM.render(<Component/>, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<divid="root"></div>
This may be groundless, but here's how to use useState
to define HTMLDivElement values on the outside.
const Component=()=>{
const [state, updateState] = React.useState("TargetValue");
constonClick=()=>{
console.log(state);
};
return(
<div>
<div>{state}</div>
<button type="button" onClick={onClick}>Debug</button>
</div>
);
};
ReactDOM.render(<Component/>, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<divid="root"></div>
© 2024 OneMinuteCode. All rights reserved.