react父子组件的传值(函数组件和类组件传值)
react父子组件的传值(函数组件和类组件传值)
一. 子传父
1. 函数组件
情景设置:假设子页面有数据要传到父页面,改变它的lable的值
父组件增加方法
const fatherComponent = ({ }) => {
const [label, setLabel] = React.useState(0);
// msg回传的内容
const changeLabel = (msg) =>// 设置label的值为msg
setLabel(msg);
}
return (
// 父组件 增加changeLabel方法,接收msg,然后改变label的值
// 可以写成 <father changeLabel={(msg) => {setLabel(msg);}}></father>
<father changeLabel={ changeLabel}></father>
)
}export default fatherComponent;
子组件使用父组件方法,传入内容
const sonComponent = ({
// 子组件使用父组件上面个定义的方法,把它传进来
changeLabel
}) => {const [label, setLabel] = React.useState(0);
// 子方法这里传值给父组件
const handleChange = (value) =>// 调用父类方法,触发 子=>父
changeLabel(value);
}
return (
// 调用父组件的changeLabel方法
// 也可以写成 <son οnchange={(value) => changeLabel(value)}></son>
<son onchange={ handleChange}></son>
)
}export default sonComponent;
2. 类组件
父子组件间通信
这种情况下很简单,就是通过 props 属性传递,在父组件给子组件设置 props,然后子组件就可以通过 props 访问到父组件的数据/方法,这样就搭建起了父子组件间通信的桥梁。
import React, { Component } from 'react';
import { render } from 'react-dom';
class GroceryList extends Component {
handleClick(i) {
console.log('You clicked: ' + this.props.items[i]);
}
render() {
return (
<div>
{ this.props.items.map((item, i) => {
return (
<div onClick={ this.handleClick.bind(this, i)} key={ i}>{ item}</div>
);
})}
</div>
);
}
}
render(
<GroceryList items={ ['Apple', 'Banana', 'Cranberry']} />, mountNode
);
div 可以看作一个子组件,指定它的 onClick 事件调用父组件的方法。
父组件访问子组件?用 refs
非父子组件间的通信
使用全局事件 Pub/Sub 模式,在 componentDidMount 里面订阅事件,在 componentWillUnmount 里面取消订阅,当收到事件触发的时候调用 setState 更新 UI。
这种模式在复杂的系统里面可能会变得难以维护,所以看个人权衡是否将组件封装到大的组件,甚至整个页面或者应用就封装到一个组件。
还没有评论,来说两句吧...