gpt4 book ai didi

reactjs - 无法引用类组件中立即解构的 props,我每次都必须使用 `this.props` 吗?

转载 作者:行者123 更新时间:2023-12-03 14:28:20 25 4
gpt4 key购买 nike

在无状态函数组件中,我们可以使用解构的 props 作为函数参数:

const Blah = ({ hello, world }) {
return <div>{hello} {world}</div>
}

这提供了非常干净的代码,不仅很明显正在传递什么 Prop ,而且我们不必到处使用 this.props

必须在 class 组件中始终使用 this.props 可能会占用整个组件的大量空间,并且使用起来不太好:

class Blah extends Component {
render() {
return (
<div>{this.props.hello} {this.props.world}</div>
)
}
}

我的问题是,我们可以对 class 组件采取什么类似的方法,这样我们就不必到处使用 this.props

我能想到的一个解决方案是解构 render 方法中的 props,但是当然,您必须对 中的每个方法都执行此操作>class 如果您想使用解构名称。

最佳答案

不,恐怕没有办法。功能组件本质上是类组件的 render() 函数,“清洁度”实际上有点相同(:

关于reactjs - 无法引用类组件中立即解构的 props,我每次都必须使用 `this.props` 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43676833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com