facebook / jsx

The JSX specification is a XML-like syntax extension to ECMAScript.
http://facebook.github.io/jsx/
1.96k stars 133 forks source link

provide `this` context in SFCs when they are invoked via `JSXMemberExpression` #69

Closed Artazor closed 7 years ago

Artazor commented 7 years ago

[holy-war question alert!] copied from https://github.com/facebook/react/issues/8714

Would it be possible to provide this context into SFCs when they are invoked via JSXMemberExpression . JSXIdentifier syntactic form?

My use-case involves unusual ES6 class usage. I'm using them as inheritable containers for SFC's, where individual components could be overridden in descendant classes.

Now I'm forced to autobind all view-methods:

class Base {
    constructor() {
        // would like to avoid these:
        this.Short = this.Short.bind(this);
        this.Full = this.Full.bind(this);
    }
   Short() { return <span>{`${this}`}</span>; }
   Full() { return <div><this.Short /></div>; }
}

class Item extends Base {
    constructor(value) {
        super();
        this.value = value;
    }
    toString() {
        return this.value;
    }
}

var obj = new Item("A");
ReactDOM.render(<obj.Full />, document.getElementById("container"));

A bit more complete example could be found at: https://jsfiddle.net/69z2wepo/67046/

I understand that it is a Holy War question about pure functions and this in JavaScript. However I'm thinking that this usage of this is legit. Just like a children in props.

It is way too ugly writing:

class Base {
   Short({self}) { return <span>{`${self}`}</span>; }
   Full({self}) { return <div><self.Short self={self} /></div>; }
}

class Item extends Base {
    constructor(value) {
        super();
        this.value = value;
    }
    toString() {
        return this.value;
    }
}

var obj = new Item("A");
ReactDOM.render(<obj.Full self={obj} />, document.getElementById("container"));

Isn't it?


I even would be happy if

<a.b.c />

would be treated as

<a.b.c self={a.b} />

just like children - provide some special member in props. However it could be problematic as it will clash with existing user code.

sebmarkbage commented 7 years ago

This is not something that is within the scope of this JSX spec since it is already expressable in the syntax form that this spec provides. Everything about the actual semantics is defined by each library. Therefore the issue on the React repo was the correct place to have the discussion.