[英]Copy Text button function in React JS
我正在處理項目 create-react-app 在這個項目中創建一些 function 但 copytext function 在下面的代碼行中沒有提到工作問題。 請檢查問題...
import React, {useState} from 'react'
export default function TextForm(props) {
const handleCopy = () => {
console.log("I am copy");
let text = document.getElementById("mybox");
text.Select();
navigator.clipborad.writetext(text.value);
}
const handleOnChange = (event) =>{
// console.log("on change");
setText(event.target.value);
}
const [text, setText] = useState('');
return (
<>
<div className='container'>
<h1>{props.heading} </h1>
<div className="mb-3">
<textarea className="form-control"
value={text} id="myBox" rows="8" onChange={handleOnChange}></textarea>
<button className="btn btn-primary mx-2 my-2" onClick={handleCopy}>Copy Text</button>
</div>
</div>
<div className="container my-3">
<h2>Your text summary</h2>
<p>{text.split(" ").length} Word and {text.length} Characters</p>
<p>{0.008 * text.split(" ").length} Minute Read</p>
<h3>Preview</h3>
<p>{text}</p>
</div>
</>
)
}
TextForm.js:16
Uncaught TypeError: Cannot read properties of null (reading 'Select')
您的代碼中存在一些問題:
text
創建了 state 並且不需要通過getElementById
和Select
來獲取它。navigator.clipborad
中不存在writetext
。 它應該是writeText
(區分大小寫)。state
。 所以,移動const [text, setText] = useState('');
到您的組件頂部。text
state 沒有value
屬性。 您可以僅通過text
訪問其值。這是編輯后的代碼:
function TextForm(props) {
const [text, setText] = useState('');
const handleCopy = () => {
navigator.clipboard.writeText(text);
}
const handleOnChange = (event) =>{
setText(event.target.value);
}
return (
<>
<div className='container'>
<h1>{props.heading} </h1>
<div className="mb-3">
<textarea className="form-control"
value={text} id="myBox" rows="8" onChange={handleOnChange}></textarea>
<button className="btn btn-primary mx-2 my-2" onClick={handleCopy}>Copy Text</button>
</div>
</div>
<div className="container my-3">
<h2>Your text summary</h2>
<p>{text.split(" ").length} Word and {text.length} Characters</p>
<p>{0.008 * text.split(" ").length} Minute Read</p>
<h3>Preview</h3>
<p>{text}</p>
</div>
</>
)
}
你有text
值所以你不需要這個
let text = document.getElementById("mybox");
text.Select();
所以也許只是這樣做
navigator.clipborad.writetext(text);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.