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>

React中,子组件可以通过props将方法传递给父组件,从而实现在子组件调用父组件的方法。具体实现步骤如下: 1.父组件中定义一个方法,该方法将作为props传递给子组件2.子组件中通过this.props来访问父组件传递过来的方法。 3.子组件调用父组件的方法,可以通过在子组件中定义一个事件处理函数,并在该函数中调用父组件传递过来的方法。 下面是一个示例代码: 父组件: ```javascript import React, { Component } from 'react'; import Child from './Child'; class Parent extends Component { handleChildEvent = (child) => { console.log('Child component mounted:', child); } render() { return ( <div> <Child onChildEvent={this.handleChildEvent} /> </div> ); } } export default Parent; ``` 子组件: ```javascript import React, { Component } from 'react'; class Child extends Component { componentDidMount() { this.props.onChildEvent(this); } sendMessage = () => { console.log('sending message'); } render() { return ( <span>Child</span> ); } } export default Child; ``` 在上面的示例代码中,父组件定义了一个handleChildEvent方法,并将该方法通过props传递给子组件。在子组件中,通过componentDidMount方法来调用父组件传递过来的方法,并将当前子组件实例作为参数传递给该方法。在子组件中,还定义了一个sendMessage方法,该方法可以在子组件中触发,并通过调用父组件传递过来的方法来实现在子组件调用父组件的方法。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值