【问题标题】:object deconstructing throws an error对象解构抛出错误
【发布时间】:2018-09-28 03:44:34
【问题描述】:

我正在将样式对象传递给组件

<Temp styles={{fontWeight: 'bold', fontSize: '1.6'}} ...otherprops />

当我尝试解构它时,它给了我一个错误提示 Cannot read property 'fontSize' of undefined

我解构的方式如下:

{({styles: {fontSize, fontWeight}}) => /* use the values */ }

我没有得到的部分是,当我记录样式时,它会显示正确的值,而当我尝试解构它时它会抛出错误。

【问题讨论】:

  • 大括号之间的左括号只是一个错字吧?
  • 不,代码看起来像这样,没有解构。 {(props) =&gt; /* do something */ }。我包装了传递的值。
  • 在你的例子中你有{({styles: ... }} ) =&gt; ;左边的( 应该在{ 之外;那里也应该只有 1 个{
  • 我理解的方式是,如果我正在解构,(道具),那么如果我这样做({styles})我提取样式,如果我这样做({styles:{fontSize,fontWeight}} ) 我从样式中提取它。
  • @vapurrmaid 它有 2 层深:props.styles.fontSizeprops.styles.fontWeight

标签: javascript reactjs ecmascript-6 styled-components


【解决方案1】:

以下为我输出16 2;我从您提供的 sn-p 中看到的唯一问题是我在 cmets 中指出的左括号:

class App extends React.Component {
  render() {
    return <Temp styles={{ fontSize: 16, fontHeight: 2 }} />;
  }
}

const Temp = ({ styles: { fontSize, fontWeight }}) => {
  console.log(fontSize, fontWeight);
  return <p>Hi</p>;
};

ReactDOM.render(
  <App />,
  document.getElementById('root')
);

【讨论】:

    猜你喜欢
    • 2021-07-27
    • 1970-01-01
    • 2018-02-18
    • 2011-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-29
    • 1970-01-01
    相关资源
    最近更新 更多