繁体   English   中英

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

[英]React.js with CoffeeScript - passing props and methods to child component

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

我使用一个全局名称空间_来存储所有控制器和视图等。

我有一个模态控制器,它创建一个模态包装器并接受内容(另一个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控制器和的另一个React组件(例如_.views.form)。 要传递所有模式方法(例如close),我需要在创建它们时将它们全部列出。

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

进行下面的操作并将父项拥有的所有内容传递给子元素是否是一种不好的做法?

_this.React.createElement @props.content, @

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

React.render(element, container, callback);

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

而且,如果您希望在孩子中可以访问父方法,则必须传递它们,或者使用Flux模式从孩子那里调用动作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM