使用类和无状态组件传递所有道具

Jen*_*eng 5 javascript reactjs

这两个组件是否完全相同?我的目的是尝试使用包装器来定制组件.不

const myComponent = (props) => {
    return (
        <OtherComponent {...props} />
    )
}
Run Code Online (Sandbox Code Playgroud)

和

class myComponent extends Component {
    const { ...rest } = this.props
    render() {
        return <OtherComponent {...rest} />
    }
}
Run Code Online (Sandbox Code Playgroud)

{...props}

相同

const { ...rest } = this.props ?

Tho*_*lle 1

是的,两种写法是相同的。中的每个键/值对this.props最终都会出现在rest变量中。

const { ...rest } = this.props您可以直接使用而不是编写this.props。

const MyComponent1 = (props) => {
  return (
    <OtherComponent {...props} />
  )
}

class MyComponent2 extends Component {
  render() {
    return <OtherComponent {...this.props} />
  }
}
Run Code Online (Sandbox Code Playgroud)