React.js与CoffeeScript - 将道具和方法传递给子组件

时间:2015-06-04 08:42:43

标签: javascript reactjs coffeescript react-jsx

我正在使用CoffeeScript处理React.js,这使我无法使用JSX(或者是吗?)。

我使用全局命名空间 _ ,我存储所有控制器和视图等。

我有一个Modal控制器,它创建一个模态包装器并接受一个内容(另一个React视图组件)。

class Modal

constructor : (@React) ->
    @wrapper = $('#modal')

create : (@content, @data, @callback) ->
    # Save this
    _this = @
    # Create the modal wrapper
    WrapperView = @React.createClass
        getInitialState : ->
            visible : false

        # After mounting
        componentDidMount : ->
           // Not important code

        componentDidUpdate : ->
            // Not important code

        componentWillUnmount : ->
            # Remove the ESC event
            _.event.lose 'CloseModal'

        close : ->
            @setState
                visible : false

        render : ->
            _.react.div 'className' : 'modal',
               _this.React.createElement @props.content, data : @props.data, close : @close

    # Renders the modal window to the prepared wrapper
    @React.render (@React.createElement WrapperView, { content : @content, data : @data }), @wrapper.get 0

让我担心的是这条线

_this.React.createElement @props.content, data : @props.data, close : @close

@ props.content是另一个传递给Modal控制器的反应组件(比如说_.views.form)。要传递所有的模态方法,例如close,我需要在创建它们时将它们全部列出。

如果没有隐式传递子元素,那么子元素是否无法访问父方法和道具?

执行以下操作并将父级所有内容传递给子元素是不是一种不好的做法?

_this.React.createElement @props.content, @

1 个答案:

答案 0 :(得分:0)

如果你传递一个完全初始化的React元素,那么你应该只是渲染它,而不是创建一个新元素。这样做是这样的:

React.render(element, container, callback);

如果您确实要创建一个新的,请根据您的版本使用React.cloneElement。使用clone元素,您可以将元素的props作为第二个参数传递,或者在早期版本的React中,有一个名为cloneWithProps的现已弃用的方法。

如果您希望父项中的方法可以在子项中访问,则必须传递它们,或者使用Flux模式来调用子项中的操作。

相关问题