javascript - 在构造函数中反应属性解构。是个好主意吗?
问题描述
通常我对渲染方法中的道具进行对象解构。
像:
render() {
const { props1, props2, props3 } = this.props;
...other code
很无聊,因为如果我需要在我的对象中定义一个方法,也许我需要这里的道具,我需要再次解构函数内的道具。
例如:
func = () => {
const { props1, props2, props3 } = this.props;
}
有一种方法可以一次性为组件执行此操作吗?也许在构造函数中?
解决方案
只做一次解构,我认为最好的方法是使用函数组件和钩子,如下例所示
export default function Banans(props) {
const {
name,
type,
color
} = props
const bananaColor = () => {
// here you can access the props without destructuring again
console.log(color)
}
return (
<div>
{name}
<button onClick={() => bananaColor()}>Banana color</button>
</div>
)
}
推荐阅读
- flutter - 如何访问有状态小部件中的方法?
- python-3.7 - python石榴贝叶斯网络初始化
- aws-amplify - 如何检索 AWS 放大数据存储的当前状态?
- java - 如何使用多个数据集或值多次运行函数?
- r - 为具有多列的数据框绘制条形图
- c# - 如何使用 C# 从 CSV 文件中删除标题和整列?
- odoo - odoo-如何保存one2many关系的相关字段
- r - 如何摆脱由 `xaringan` 幻灯片中的 `kableExtra` 生成的表格内的反抽动?
- javascript - React 不在 DOM 上渲染任何东西
- java - 通过 https 将请求从 Nginx 重定向到 Spring boot App