如何将数据从子组件发送到父组件的父组件(react)



我想将同义词变量发送到我的Dictionary.js组件,这样当我单击按钮时,它将在我的API调用中使用该词。

组件没有直接链接。它是父母的一个孩子。请参考我的开源代码。

我知道需要一个回调函数,但我无法让它发挥作用。

export default function Synonyms(props) {
function searchSynonym(event) {
let synonym = event.target.innerHTML;
}
if (props.synonyms.length > 0) {
return (
<div className="Synonyms">
<h4>Synonyms:</h4>
{props.synonyms.map((synonym, index) => {
if (index < 10) {
return (
<button
type="button"
class="btn btn-light btn btn-outline-dark"
key={index}
onClick={searchSynonym}
>
{synonym}
</button>
);
} else {
return null;
}
})}
</div>
);
} else {
return null;
}
}

你可以在Github上找到完整的代码。非常感谢您的帮助。非常感谢。

您可以使用道具来管理这个场景,但它是嵌套的。现在是使用全局状态管理的时候了。管理状态有几个选项。您可以使用内置的状态管理工具,如useContext和useReducer,也可以添加依赖项,如redux工具箱或其他工具。

查看文档,了解如何使用usecontext![https://reactjs.org/docs/hooks-reference.html#usecontext][1]

简单地(在没有实现全局状态管理的情况下(通过许多组件传递变量的方法是通过组件串接道具,例如:

import React from 'react'
const [synonym, setSynonym] = useState('')
const HighestLevelVarIsNeededComponent = () => {
return (
<>
<MiddleLevel setSynonym={setSynonym}/>
<div>{synonym}</div>
</>
)
}
export default HighestLevelVarIsNeededComponent

import React from 'react'
const MiddleLevel = (props) => {
return (
<>
<LastLevel setSynonym={props.setSynonym} />
</>
)
}
export default MiddleLevel

import React from 'react'
const LastLevel = (props) => {
// find synonym here
let newSynonym = 'intersting'
props.setSynonym(newSynonym)
//after doing the above it will update the synonym variabile at the highest level
return (
<>
<div></div>
</>
)
}
export default LastLevel

最新更新