如何创建 UI 元素的列表,每个元素的对齐方式不同?

How can I create a list of UI elements, each aligned differently?

假设我想创建一个包含 UI 个元素的列表,并且我希望每个元素以不同方式对齐。我在想象这样的事情:

<List>
<Button Alignment="right"/>
<Panel Alignment="left"/>
<Video Alignment="center"/>
</List>

如何做到最好?最好不要对每个子元素添加对齐 属性 的特殊处理。

有很多方法可以在 React 中完成类似的事情,没有特定的方法一定是 "best."

我绝对推荐看一下:

http://facebook.github.io/react/docs/getting-started.html

这是一个使用简单混入的想法。

var List = React.createClass({
    render: function() {
        return (
            <div>
                <Button alignment="right" />
                <Panel alignment="left" />
                <Video alignment="center" />
            </div>
        );
    }
});

var Button = React.createClass({
    mixins: [AlignmentMixin],
    render: function() {
        return (            
            <Button  { ... this.props } className={ this.renderAlignment() } />
        );
    }
});

var AlignmentMixin = {
    renderAlignment: {
        // whatever you'd like, just an example
        // of constructing a class name called box-right/left/center
        return "box-" + this.props.alignment;
    }
}

不存在可全局应用于所有类型的 Angular 指令的等价物。 React 采用不同的方法,通过设计(目前)期望组件呈现一个众所周知的接口,并且不能由组件的消费者任意扩展。这意味着 ReactJS 中的组件只是它所说的和可以做的,父组件只能通过在组件实例上设置属性来影响它的行为。

在我上面提供的示例中,我明确地将 "alignment" mixin 添加到 Button。没有它,按钮将不具有对齐功能。

当然,如果没有可以像我上面显示的那样简单地应用的通用模式,您可以只向按钮添加必要的代码来进行对齐。

有些人甚至可能不使用 mixin,因为他们宁愿将 "is a" Button 的代码仅放在名为 Button.js 的文件中(例如)。 UI 和行为不会像在 angular 应用程序中那样潜在地分布在多个文件中(其中指令可能位于不同的文件中,并且很难发现可能应用于任何给定元素的内容)。

事实上,来自“why react page”:

Since they're so encapsulated, components make code reuse, testing, and separation of concerns easy.