在这种情况下如何在此处添加解构

How do I add destructuring here in the case

我学习 React 和 JavaScript。我偶然发现了这个 Eslint 建议我像图像警告建议的那样进行解构,但我应该在哪里添加它。我尝试 const { errorComponent }= props; 但这在 const

中不起作用

代码:

import '../../styles/error.scss';

const Error = props => (
    <div className="error-message">
        {props.errorComponent ? <props.errorComponent {...props} /> : <p className="alert">Unable to preview file</p>}
    </div>
);

export default Error;

除我的评论外,您的组件可能看起来像这样:

const Error = ({ errorComponent: Component, ...props }) => (
  <div className="error-message">
    {Component ? (
      <Component {...props} />
    ) : (
      <p className="alert">Unable to preview file</p>
    )}
  </div>
);

更好的选择是使用 children 道具。

const Error = ({ children }) => (
  <div className="error-message">
    {children || <p className="alert">Unable to preview file</p>}
  </div>
);

据我所知,你可以像这样解构它

const Error = props => {
  const {errorComponent, otherProperty} = props
  return (<div className="error-message">
      {errorComponent ? <errorComponent {otherProperty} /> : <p className="alert">Unable to preview file</p>}
  </div>)
}
  


export default Error;

试试这个方法。

  const Error = ({ errorComponent, ...props }) => {
        const ErrorComponent = errorComponent;
        return (<div className="error-message">
            {errorComponent ? <ErrorComponent {...props} /> : <p className="alert">Unable to preview file</p>}
        </div>)
      }

<errorComponent> - 它不会按预期工作,因为所有自定义组件都应以正楷开头(如果不是,react 会将其视为 in-build Html 标签)