首页 > 解决方案 > 在构造函数中反应属性解构。是个好主意吗?

问题描述

通常我对渲染方法中的道具进行对象解构。

像:

render() {
const { props1, props2, props3 } = this.props;
...other code

很无聊,因为如果我需要在我的对象中定义一个方法,也许我需要这里的道具,我需要再次解构函数内的道具。

例如:

func = () => {
  const { props1, props2, props3 } = this.props;
}

有一种方法可以一次性为组件执行此操作吗?也许在构造函数中?

标签: javascriptreactjs

解决方案


只做一次解构,我认为最好的方法是使用函数组件和钩子,如下例所示

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>
    )
}

推荐阅读