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

Ilj*_*lja 13 javascript object ecmascript-6 reactjs react-jsx

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

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>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

我成功地破坏了,this.props并且可以在渲染中使用它们,但是如果我需要在它之外使用道具值,即内部someFunction()我不确定如果我移出constant { ... }并包括export default class Input extends React.Component {一行一行会产生什么后果.这仍然有效吗?

Piy*_*oor 8

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

这是一种保持渲染或功能的推荐方法,因为你的父组件可以改变状态,这将导致你的孩子被重新渲染,所以你需要为每个渲染提供新的道具.


Tha*_*you 7

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

那么你不能这样做.解构只能分配局部变量,因此您需要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>
)
Run Code Online (Sandbox Code Playgroud)