无法在 class 组件中引用立即解构的 props,我是否必须每次都使用 `this.props`?
Unable to refer to immediately destructured props in class component, do I have to use `this.props` every time?
在无状态函数组件中,我们可以使用解构的props
作为函数参数:
const Blah = ({ hello, world }) {
return <div>{hello} {world}</div>
}
这提供了非常干净的代码,不仅传递的 props 很明显,而且我们不必在任何地方都使用 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
中的每个方法都这样做你想使用解构后的名字。
不,恐怕没有办法。功能组件本质上是 class 组件的 render()
功能,"cleaniness" 实际上有点相同 (:
在无状态函数组件中,我们可以使用解构的props
作为函数参数:
const Blah = ({ hello, world }) {
return <div>{hello} {world}</div>
}
这提供了非常干净的代码,不仅传递的 props 很明显,而且我们不必在任何地方都使用 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
中的每个方法都这样做你想使用解构后的名字。
不,恐怕没有办法。功能组件本质上是 class 组件的 render()
功能,"cleaniness" 实际上有点相同 (: