父子组件 (父–>子)
在父组件中:
import React from 'react'
import ChildCom from './childCom.js'
class ParentCom extends React.Component {
render() {
return (
<div>
<h1>父组件</h1>
<ChildCom content={'我是父级过来的内容'}/>
</div>
)
}
}
export default ParentCom;
在子组件中
import React from 'react'
class ChildCom extends React.Component {
render() {
return (
<div>
<h2>子组件</h2>
<div>
{this.props.content}
</div>
</div>
)
}
}
export default ChildCom;
export default ParentCom;
通过上面例子可以看出,在父组件中,我们引入子组件,通过给子组件添加属性,来起到传参的作用,子组件可以通过props获取父组件传过来的参数
父子组件 (子–>父)
在父组件中:
import React from 'react'
import ChildCom from './childCom.js'
class ParentCom extends React.Component {
state = {
getChildValue: ''
}
getChildValue(value) {
this.setState({
getChildValue: value
})
}
render() {
return (
<div>
<h1>父组件</h1>
<div>子组件过来的值为:{this.state.getChildValue}</div>
<ChildCom onValue={this.getChildValue.bind(this)}/>
</div>
)
}
}
export default ParentCom;
在子组件中:
import React from 'react'
class ChildCom extends React.Component {
valueToParent(value) {
this.props.onValue(value); //onValue是父组件的函数 即在子组件调用父组件的方法并传值
}
render() {
return (
<div>
<h2>子组件</h2>
<div>
<a onClick={this.valueToParent.bind(this,123)}>向父组件传值123</a>
</div>
</div>
)
}
}
export default ChildCom;
子组件向父组件传参,其实就是在父组件中给子组件添加一个属性,这个属性的内容为一个函数,然后在子组件中调用这个函数,即可达到传递参数的效果
兄弟组件
通过状态提升的方法 因为他们有共同的父组件
父组件调用子组件中的方法 ES6
父组件
class Daddy extends React.Component {
render() {
return <Hello ref={child => this._child = child} />
}
componentDidMount() {
this._child.sayHello();
}
}
子组件
class Hello extends React.Component {
sayHello = () => {
console.log('hello');
};
render() {
return 'child component';
}
}