为依赖于props的Reason-React组件创建样式的惯用方法是什么?

问题描述 投票:1回答:2

要学习,我正在研究一个简单的“Things 2 Do”应用程序(参见source code on GitHub)。

我有一个TodoItem组件,当项目完成时应该以透视样式呈现。

我尝试通过创建一个具有各种样式的记录来解决这个问题,类似于CSS类,一个根样式和一个已完成项目。

type style = {
  root: ReactDOMRe.style,
  completed: ReactDOMRe.style
};

let styles = {
  root: ReactDOMRe.Style.make(), /* add root styles here */
  completed: ReactDOMRe.Style.make(~opacity="0.666", ~textDecoration="line-through", ())
};

如果prop完成是真的,我将根样式与完成的样式结合起来,否则我只使用root,如下所示:

let style = styles.root;
let style = item.completed ? ReactDOMRe.Style.combine(style, styles.completed) : style;

这有效,但看起来很笨重,所以我想知道:是否有更优雅的解决方案,例如使用变量和switch语句?

为依赖于props的Reason-React组件创建样式的惯用方法是什么?

这是我的组件的完整代码:

type item = {
  id: int,
  title: string,
  completed: bool
};

type style = {
  root: ReactDOMRe.style,
  completed: ReactDOMRe.style
};

let str = ReasonReact.stringToElement;

let component = ReasonReact.statelessComponent("TodoItem");

let styles = {
  root: ReactDOMRe.Style.make(), /* add root styles here */
  completed: ReactDOMRe.Style.make(~opacity="0.666", ~textDecoration="line-through", ())
};

let make = (~item: item, ~onToggle, _) => {
  ...component,
  render: (_) => {
    let style = styles.root;
    let style = item.completed ? ReactDOMRe.Style.combine(style, styles.completed) : style;
    <div style>
      <input
        _type="checkbox"
        onChange=((_) => onToggle())
        checked=(Js.Boolean.to_js_boolean(item.completed))
      />
      <label> (str(item.title)) </label>
    </div>
  }
};
css reactjs reason reason-react
2个回答
3
投票

我认为还有什么东西可以被称为惯用语。该区域正在迅速变化,甚至我对如何改进它有一些我自己的想法,但这或多或少我现在使用bs-css做的方式:

module Styles = {
  open Css;

  let root = completed => style([
    color(white),
    opacity(completed ? 0.666 : 1.),
    textDecoration(completed ? LineThrough : None)
  ]);
}

...

  render: _self =>
    <div className=Styles.root(item.completed)>
      ...
    </div>

0
投票

现在,我为我的组件设计样式的方式还可以。在Reason中设置React组件并不是真正的惯用方法。

原因文件has this to say

由于CSS-in-JS现在风靡一时,我们很快会推荐我们的官方选择。与此同时,对于内联样式,还有ReactDOMRe.Style.make API

© www.soinside.com 2019 - 2024. All rights reserved.