react⽗组件调⽤⼦组件的⽅法⽗⼦组件传值注意点写在上边⽐较醒⽬
⽅法必须写成箭头函数,不然this的指向会出问题。
(不⽤箭头函数的话要⽤this.fn.bind(this)修正this的指向)
⽗组件向⼦组件传值/⽅法⽐较简单,都是在属性中传然后在⼦组件中props获取。
⼦组件向⽗组件传值是通过事件进⾏传值。
⽗组件向⼦组件传值
//⽗组件中
import React,{ Component }from"react";
import Child from"./Child";
class Dad extends Component {
constructor(props){
super(props);
this.state ={
arr:["暴富","暴瘦"],
}
}
render(){
return(
<div>
//写在⼦组件的属性中
<Child arr={this.state.arr}></Child>
</div>
)
}
}
export default Dad;
//⼦组件中
import React,{ Component }from"react";
class Child extends Component {
constructor(props){
super(props);
}
render(){
return(
<div>
<ul>
{
//再⽤props获取
this.props.arr.map(el=>{
return(
<li key={el}>{el}</li>
)
})
}
</ul>
</div>
)
}
}
export default Child;
在⼦组件中调⽤⽗组件中的⽅法
//⽗组件
import React,{ Component }from"react";
import Child from"./Child";
class Dad extends Component {
constructor(props){
super(props);
}
dadFn=()=>{
console.log("我是⽗组件中的⽅法")
}
render(){
return(
<div>
<Child dadFn={this.dadFn}></Child>
</div>
)
}
}
export default Dad;
//⼦组件
import React,{ Component }from"react";
class Child extends Component {
constructor(props){
super(props);
}
render(){
return(
<div>
<button onClick={this.props.dadFn}>在⼦组件中调⽤⽗组件中的⽅法</button> </div>
)
}
}
export default Child;
⼦组件向⽗组件传值
constructor(props){
super(props);
this.state ={
txt:"我是尼爸爸"
}
}
fn=(data)=>{
this.setState({
txt:data
})
}
render(){
return(
<div>
<Child cfn={this.fn}></Child>
<p>{}</p>
</div>
)
}
}
export default Dad;
//⼦组件
import React,{ Component }from"react";
class Child extends Component {
constructor(props){
super(props);
}
fn=(data)=>{
this.props.cfn(data);
}
render(){
return(
<div>
//通过事件进⾏传值
<button onClick={()=>{this.fn("我是⼉⼦")}}>⼦组件向⽗组件传值</button> </div>
)
}
}
export default Child;
⽗组件调⽤⼦组件中的⽅法
constructor(props){
super(props);
this.state ={
arr:["暴富","暴瘦"],
txt:"我是尼爸爸"
}
}
onRef=(ref)=>{
this.Child=ref;
}
click=()=>{
this.Child.childFn();
}
render(){
return(
<div>
<Child onRef={Ref}></Child>
react组件之间通信
<button onClick={this.click}>⽗组件调⽤⼦组件中的⽅法</button>
</div>
)
}
}
export default Dad;
//⼦组件
import React,{ Component }from"react";
class Child extends Component {
constructor(props){
super(props);
}
componentDidMount(){
Ref(this)
}
childFn=()=>{
console.log("我是⼦组件中的⽅法")
}
render(){
return(
<div>
</div>
)
}
}
export default Child;

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。