【问题标题】:Implementing a stateless child component in React.js在 React.js 中实现无状态子组件
【发布时间】:2015-07-22 14:35:37
【问题描述】:

我正在尝试实现一个无状态的 React 组件,它将在页脚中显示方向(作为文本)——我称之为 Direction 组件。该组件旨在包含在其他父组件中,代表不同的页面,这些页面作为 Direction 组件呈现的 props 传入必要的方向。

// direction.js 
'use strict';

var React = require('react');

var Direction = React.createClass({

    propTypes: {
        directionText: React.PropTypes.string.isRequired
    },

    render: function() {
        return (
            <div className="direction">
                <p className="direction-text">
                    {this.props.directionText}
                </p>
            </div>
        );
    }

});

module.exports = Direction;


// controller.js
var DirectionController = {
  // not sure how to configure it
};

我不确定应该如何配置controller

  1. 我什至需要controller,因为这个组件只会呈现文本并且不处理用户交互性?

  2. 这个组件应该像我想的那么简单吗?

我是 React 新手。

【问题讨论】:

  • 我不清楚DirectionController 的目的是什么。你能详细说明一下吗?
  • 这是我的问题。 1(上)。很可能不需要控制器,因为没有用户交互性。
  • 你是否需要它取决于它的用途。你到底打算用它做什么?它与(不存在)交互性有什么关系?但也许我不能立即看到目的这一事实意味着你不需要它。
  • 即使您没有用户交互性,您也需要从某个地方获取您计划传递给您的 Direction 组件的方向(否则您可能拥有方向不变的静态 HTML)。那么方向的来源是什么?
  • @BinaryMuse 虽然 Angular 和 Ember 定义的控制器并不常见,但“视图控制器”的概念却很常见。一个对渲染知之甚少的组件,但它对数据和状态了解很多,并且只是将其传递给对渲染了解很多,而对数据和状态了解不多的组件。

标签: javascript user-interface components reactjs


【解决方案1】:

您只需在需要时将 Direction 组件包含在渲染中,并在属性 directionText 中传递您想要显示的内容

render: function() {
    <div className="whatever-class">
      <Direction directionText="Some text to show" /> 
      <Direction directionText="Some some more more text text" /> 
    </div>
)

【讨论】:

    猜你喜欢
    • 2016-04-19
    • 1970-01-01
    • 1970-01-01
    • 2019-04-05
    • 2020-02-12
    • 1970-01-01
    • 1970-01-01
    • 2016-06-12
    • 2019-11-02
    相关资源
    最近更新 更多