如何将 div 的 innerText 值传递给 React 中的父组件

How to pass innerText value of a div to a parent Component in React

大家好, 我在将 innerText 值传递给父组件时遇到问题

下面是父组件和子组件的截图

Parent Component which I want to receive the innerText value

       <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>

Child Component which I want to send the innerText value from

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>
)
}

state I want to update after receiving the value

const [value, setValue] = useState('i brush')

屏幕截图也可以通过 link 获得正确的视图

Parent:

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>

Child:

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 将保存在您的 parent comp 变量中:text