1. 程式人生 > >React 元件之間 事件呼叫(父元件呼叫子元件)

React 元件之間 事件呼叫(父元件呼叫子元件)

<!DOCTYPE html>
<html>
  <head>
    <script src="build/react.js"></script>
    <script src="build/react-dom.js"></script>
    <script src="build/browser.min.js"></script>
  </head>
  <body>
    <div id="example"></div>
    <script type="text/babel">
	
var HelloMessage = React.createClass({
	getDragonKillingSword: function(){
		alert("OK");
	},
  render: function() {
    return <div> <h1>Hello {this.props.name}</h1>  <button onClick={this.getDragonKillingSword}>OK</button></div>
  }
});


var ImDaddyComponent = React.createClass({
	getDS: function(){
		//父元件呼叫子主鍵進行通訊
		this.refs.getSwordButton.getDragonKillingSword();
	},
    render: function(){
        return (
            <div>
                <HelloMessage name="John" ref="getSwordButton" />
				<button onClick={this.getDS}>OK2</button>
            </div>
        );
    }
});

ReactDOM.render(
  <ImDaddyComponent  />,
  document.getElementById('example')
);
    </script>
  </body>
</html>