大家好,我在將 innerText 值傳遞給父組件時遇到問題
下面是父組件和子組件的截圖
我想接收 innerText 值的父組件
<input type="text"
value={value}
className='display_text'
ref={outputRef}
readOnly
/>
<div className="flex">
<PaperLetter sd={setValue}>teeth.</PaperLetter>
<PaperLetter>brush</PaperLetter>
<PaperLetter>my</PaperLetter>
<PaperLetter>i</PaperLetter>
</div>
我想從中發送 innerText 值的子組件
export default function PaperLetter(props) {
const [clicked, setclicked] = useState(false);
const letterRef = useRef();
const btnClicked =()=>{
//Change the className of the btn clicked to active
setclicked(true);
//Get the value of the letter btns clicked
const getValue = letterRef.current.innerText;
// How to pass this value to my parent component inorder to
update a state in the parent component is the major chanllege
}
return (
<p className={clicked ? 'letter clicked': 'letter'}
onClick={btnClicked} ref={letterRef} >{props.children}
</p>
)
}
收到值后我想更新的狀態
const [value, setValue] = useState('i brush')
螢屏截圖也可通過鏈接獲得以正確查看
uj5u.com熱心網友回復:
家長:
const [text, setText] = useState('');
const handleInnerText = (innerText) => {
setText(innerText);
}
<input type="text"
value={value}
className='display_text'
ref={outputRef}
readOnly
/>
<div className="flex">
<PaperLetter handleInnerText={handleInnerText} sd={setValue}>teeth.</PaperLetter>
<PaperLetter>brush</PaperLetter>
<PaperLetter>my</PaperLetter>
<PaperLetter>i</PaperLetter>
</div>
孩子:
export default function PaperLetter(props) {
const [clicked, setclicked] = useState(false);
const letterRef = useRef();
const btnClicked =()=>{
//Change the className of the btn clicked to active
setclicked(true);
//Get the value of the letter btns clicked
const getValue = letterRef.current.innerText;
// How to pass this value to my parent component inorder to
update a state in the parent component is the major chanllege
props.handleInnerText(getValue);
}
return (
<p className={clicked ? 'letter clicked': 'letter'}
onClick={btnClicked} ref={letterRef} >{props.children}
</p>
)
}
現在innerText將保存在您的父 comp 變數中:文本
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/414869.html
標籤:
上一篇:如何知道何時播放實際音頻?
