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

问题描述 投票:0回答:1

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

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

我想接收 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>

我想从中发送 innerText 值的子组件 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')

也可以通过链接获得屏幕截图以进行正确查看

reactjs dom react-hooks react-props
1个回答
1
投票

家长:

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 将保存在您的父组件变量中:文本

© www.soinside.com 2019 - 2024. All rights reserved.