简体   繁体   中英

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

I am working with React.js using CoffeeScript, which makes it impossible for me to use JSX (or does it?).

I use a global namespace _ where I store all controllers and views etc.

I have a Modal controller that creates a modal wrapper and accepts a content (another React view component).

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

What worries me a bit is this line

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

@props.content is another react component passed to the Modal controller and (lets say _.views.form). To pass all the modals methods such as close I would need to list them all when I create them.

Is there no way for the child element to access the parents methods and props without them being implicitly passed?

Would it be a bad practice to do the below and pass everything the parent has to the child element?

_this.React.createElement @props.content, @

If your'e passing it a fully initialized React element, then you should just be rendering it, not creating a new one. That's done like so:

React.render(element, container, callback);

If you do want to create a new one, you'd use React.cloneElement depending on your version. With clone element you can pass the element's props as the second parameter, or in earlier versions of React there was a now deprecated method called cloneWithProps .

And if you want methods from the parent to be accessible in the child, you must pass them or alternatively use a Flux pattern where you call an action from the child.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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