如何在React无状态组件中编写和访问函数

时间:2018-12-17 08:20:52

标签: reactjs react-component

我想使用无状态React组件以CSS样式编写和访问函数/ const。

我做了以下实现,但没有成功:

class Weapon : Item {

  public string Attack { get; set; }
  public string Type { get; set; }

  public Weapon() {
  }

  public Weapon(string itemName, string cost) : base(itemName, cost) {
  }

  public override void SetItemPropertiesLabels(Panel panel) {
    Label lbl = new Label();
    lbl.AutoSize = true;
    lbl.Text = "Weapon Type: " + Type + "  Attack: " + Attack;
    lbl.Location = new System.Drawing.Point(15, 50);
    panel.Controls.Add(lbl);
  }
}

请帮助编写正确的解决方案。

谢谢

1 个答案:

答案 0 :(得分:1)

您可以通过调用直接访问您的函数。即:

stroke: setPercentageColor()

这是一个简单的工作示例:

const App = () => {
  const setTextColor = () => "#ca2626";
  return (
    <div>
      <Foo
        styles={{ colors: { text: setTextColor(), background: "black" } }}
      />
    </div>
  );
};

const Foo = (props) => {
  const { styles } = props;
  return (
    <div
      style={{
        color: styles.colors.text,
        backgroundColor: styles.colors.background,
      }}
    >
      Foo
    </div>
  );
};

ReactDOM.render(
  <App />,
  document.getElementById("root")
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="root"></div>