为整个组件正确解构 this.props

Correctly destructuring this.props for the whole component

我今天遇到一个问题,请考虑以下组件:

export default class Input extends React.Component {
  someFunction() {
    console.log(this.props.value)
  }

  render () {
    const { type, value, required } = this.props
    return (
      <div className={cx('Input')}>
        <input type={type} value={value} required={required} />
      </div>
    )
  }
}

我成功地解构了 this.props 并且可以在渲染器中使用它们,但是如果我需要在它之外使用道具值怎么办,即在 someFunction() 里面我不确定会有什么后果如果我移出 constant { ... } 并包含在 export default class Input extends React.Component { 行之后。这仍然有效吗?

也许考虑将其更新为功能组件。

function someFunction(props) {
  console.log(props.value)
}

function Input(props) {
  const { type, value, required } = props;

  someFunction(props); // logs props.value

  return (
    <div className={cx('Input')}>
      <input type={type} value={value} required={required} />
    </div>
  )
}

export default Input;

如果你把它移到外面,它们将是 null ,因为那时构造函数不会被调用。

将其保留在渲染或函数中是一种推荐方法,因为您的父组件可以更改状态,这将导致您的子组件重新渲染,因此您需要为每个渲染提供新的道具。

Correctly destructuring this.props for the whole component

好吧,你不能那样做。解构只能分配局部变量,因此您需要在每个函数中解构 props。否则写this.props.value也没什么问题。在有助于提高可读性时使用解构,而不仅仅是因为您不想输入 this.props.

我会这样写你的代码

// import cx from whatever

const someFunction = value=> console.log(value)

export const Input = ({type, value, required}) => (
  someFunction(value),
  <div className={cx('Input')}>
    <input type={type} value={value} required={required} />
  </div>
)