【发布时间】:2021-09-30 10:26:28
【问题描述】:
我搜索了类似的问题,但没有一个能解决我的疑问。在这种情况下,如何将“this”更改为反应功能组件:<SimpleStorage parent={this}/>,其中该组件属于一个库(称为 react-simple-storage)并编写在功能组件内。
我看到的所有示例都涉及this.state 或this.object 或this.function,但没有一个是关于this 单独的。
const Books = () => {
...
return <Router>
<SimpleStorage parent={this}/>
<Routes/>
</Router>
当我尝试以这种方式运行时,他运行但控制台抛出:
No "parent" prop was provided to react-simple-storage. A parent component's context is required in order to access and update the parent component's state.
Try the following: <SimpleStorage parent={this} />
如何设置功能组件的组件状态?我必须在父组件中实例化一个变量吗?有什么可以做的吗?
【问题讨论】:
-
Books是一个函数组件,它使用箭头函数。箭头函数没有自己的this。 -
不要将 function 组件与 functional 编程混淆;它们是非常不同的东西。
-
看起来那个库刚刚过时,有一个废弃的 PR 来支持基于函数的组件:github.com/ryanjyost/react-simple-storage/pull/30。
标签: javascript reactjs react-hooks react-functional-component