react icon indicating copy to clipboard operation
react copied to clipboard

Does bound function being reused across multiple instance of React Component ?

Open qingweibinary opened this issue 10 years ago • 6 comments

Hi, I met some problem with event handler binding in React ES6 class syntax

// Render() of parent component
render() {
        const { trades, contracts } = this.props;
        const allID = Object.keys(trades);
        return (
            <div>
                {allID.map(id => {
                        return (
                            <TradePanel
                                key={id}
                                id={id}
                                {...this.props}
                            />
                        );
                    }
                })}
            </div>
        );

// child Component class
class TradePanel extends Component {
        method1(e) {
                const { id } = this.props;
                ....
        }

        render() {
                return <input onChange={::this.method1} />
        }
}

Problem happens when I create 2nd instance of child component, method1 is incorrectly bounded to this of 1st instance.

Other props are pass properly, the problems are with event handlers.

When render() is called, will the binding be re-evaluate? If parent component rerender, does it destroy the old children and reconstruct a new one ?

Regards ~

qingweibinary avatar Jan 21 '16 10:01 qingweibinary

Additional findings ~

This problem only happens on <input type="radio"> text input works properly

qingweibinary avatar Jan 21 '16 11:01 qingweibinary

There is no autobinding for ES6 classes so any binding issues are likely happening at the transform level (the :: binding syntax is not a standard at this point). If you can reproduce in a test case on jsfiddle using more supported syntaxes, it will be easier to see if maybe there's a bug in React.

zpao avatar Jan 21 '16 23:01 zpao

OK, I'll do it, but it's gonna take sometime, as I am occupied now, thanks =)

qingweibinary avatar Jan 22 '16 00:01 qingweibinary

Unreproducible

qingweibinary avatar Jan 25 '16 02:01 qingweibinary

@qingweibinary I'm having a similar issue, were you ever able to figure it out?

quantizor avatar Mar 21 '16 21:03 quantizor

@yaycmyk

Would you try perform the binding in constructor instead of inside render() ?

qingweibinary avatar Mar 22 '16 01:03 qingweibinary