Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
97 views
in Technique[技术] by (71.8m points)

javascript - Why no parentheses on a function

Any help or hint would be greatly appreciated. Why don't use parenthese in method call? If I use parenthese "onInputChange()" the method is called when I loaded the page. After the call, if I type anything in the input box and click outside the "onInputChange()" method is not call.

If I don't use parenthese "onInputChange" the method is not called when I loaded the page, why is that so? But after load and I type something in input box and click outside the method "onInputChange" is call.

wrong way:

  <input type="text" onChange={this.onInputChange()} />

correct way:

<input type="text" onChange={this.onInputChange} />

SearchBar.js

import React from 'react';

class SearchBar extends React.Component {
  onInputChange() {
    console.log('onInputChange');
  }

  render() {
    return (
      <div className="ui segment">
        <form className="ui form">
          <div className="field">
            <label>Image Search</label>
            <input type="text" onChange={this.onInputChange()} />
          </div>
        </form>
      </div>
    );
  }
}

export default SearchBar;
question from:https://stackoverflow.com/questions/65516967/why-no-parentheses-on-a-function

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

When the code gets compiled from JSX to pure JS, many props are simply object properties. For example:

<input type="text" onChange={this.onInputChange()} />

This gets compiled to:

React.createElement("input", {
  type: "text",
  onChange: this.onInputChange()
});

Just like in ordinary JS, if you invoke a function directly inside the prop or object, that function will be invoked when the object is evaluated for the first time.

const fn = () => {
  console.log('fn running');
  return 'foo';
};
const obj = {
  prop: fn()
};
console.log('obj is', obj);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...