一般 JS onclick用法,與React的差異比較
<button onclick="myFunction()">Click me</button> <!-- 可以觸發 --> <button onclick="myFunction">Click me</button> <!-- 不行 --> <p id="demo"></p> <script> function myFunction() { document.getElementById("demo").innerHTML = "Hello World"; } </script>
https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onclick
class App extends React.Component { handleClick = () => { console.log("test"); }; render() { return ( <div> <button onClick={() => this.handleClick()}>Click me</button> <button onClick={this.handleClick}>Click me</button> {/*正常*/} <button onClick={this.handleClick()}>Click me</button> {/*會自動觸發一次*/} </div> ); } }
@copyright MRcodingRoom
觀看更多文章請點MRcoding筆記
觀看更多文章請點MRcoding筆記