大家好, 我在将 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')
也可以通过链接获得屏幕截图以进行正确查看
家长:
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 将保存在您的父组件变量中:文本