<div id="correspond"></div>
<script type="text/babel">
///子組件
var HelloMessage = React.createClass({
childMethod: function(){
alert("組件之間通信成功");
},
render: function() {
return <div> <h1>Hello {this.props.name}</h1> <button onClick={this.childMethod}>子組件</button></div>
}
});
//父組件
var ImDaddyComponent = React.createClass({
getDS: function(){
//調(diào)用組件進(jìn)行通信
this.refs.getSwordButton.childMethod();
},
render: function(){
return (
<div>
<HelloMessage name="John" ref="getSwordButton" />
<button onClick={this.getDS}>父組件</button>
</div>
);
}
});
ReactDOM.render(
<ImDaddyComponent />,
document.getElementById('correspond')
);
</script>
這種方式在新版本react是走不通的檬贰,需要像下面這種操作
import React, {Component} from 'react';
export default class Parent extends Component {
render() {
return(
<div>
<Child onRef={this.onRef} />
<button onClick={this.click} >click</button>
</div>
)
}
onRef = (ref) => {
this.child = ref
}
click = (e) => {
this.child.myName()
}
}
class Child extends Component {
componentDidMount(){
this.props.onRef(this)
}
myName = () => alert('xiaohesong')
render() {
return ('woqu')
}
}