【问题标题】:Double curly braces in React expressionReact 表达式中的双花括号
【发布时间】:2020-06-14 21:02:03
【问题描述】:

我从 React 文档中发现了以下代码:

import {ThemeContext} from './theme-context';

class ThemedButton extends React.Component {
  render() {
    let props = this.props;
    let theme = this.context;
    return (
      <button
        {...props}
        style={{backgroundColor: theme.background}}
      />
    );
  }
}
ThemedButton.contextType = ThemeContext;

export default ThemedButton;

为什么样式有双花括号而不是只有一个?:

style={{backgroundColor: theme.background}}

【问题讨论】:

标签: reactjs


【解决方案1】:

内花括号是一个对象,与:

const myStyles = {backgroundColor: theme.background};

然后:

<button style={myStyles} />

外面的花括号包裹着一个表达式,它可能是一个变量、一个对象、一个函数,或者任何可以解析为一个值的东西。

【讨论】:

    【解决方案2】:

    假设您正在传递一个 prop 来响应组件。

    &lt;Component value={"somevalue"} /&gt; 这里的值是字符串,但你仍然需要花括号作为格式。 常量 a = {a: 1} &lt;Component value={a} /&gt;这里是对象如果你嵌入对象&lt;Component value={{a: 1}} /&gt;

    同样,样式是需要传递给 React 元素的对象。

    你也可以

    const style = { myClass: {color: "red"} } <div style={style.myClass} />

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-08
      相关资源
      最近更新 更多